Practice › Dynamic Programming
Word Break
Medium · Dynamic Programming · Asked at Amazon, Google, Meta, Microsoft, Apple
Print YES if the string s can be split into a sequence of one or more dictionary words (a word may be used any number of times), otherwise NO.
Input
First line: n. Second line: the n dictionary words. Third line: s.
Output
YES or NO.
Constraints
- 1 ≤ n ≤ 1000
- 1 ≤ word length ≤ 20
- 1 ≤ |s| ≤ 3000
- only lowercase letters
ok[i] is true when the first i letters can be split. ok[i] = some word w ends at i with ok[i − |w|] true. Only words up to length 20 need checking at each i.
Example 1
Input
2 leet code leetcode
Output
YES
Example 2
Input
5 cats dog sand and cat catsandog
Output
NO
Hints
- If the first j letters can be split, and s[j..i) is a word, then the first i letters can be split.
- ok[0] = true for the empty prefix.
- Words are at most 20 letters long, so only 20 values of j matter for each i.
Approach
Put the dictionary in a hash set. For i from 1 to |s|, try every length l ≤ 20: if ok[i − l] and s[i − l..i) is in the set, mark ok[i] and stop. The answer is ok[|s|]. Limiting l to the longest word keeps the work at O(|s| · 20) substring lookups instead of O(|s|²).
Complexity: O(|s| · L²) time with L = 20 · O(|s| + dictionary) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
unordered_set<string> dict;
for (int i = 0; i < n; i++) {
string w;
cin >> w;
dict.insert(w);
}
string s;
cin >> s;
int m = s.size();
vector<bool> ok(m + 1, false);
ok[0] = true;
for (int i = 1; i <= m; i++)
for (int l = 1; l <= 20 && l <= i && !ok[i]; l++)
if (ok[i - l] && dict.count(s.substr(i - l, l))) ok[i] = true;
cout << (ok[m] ? "YES" : "NO") << "\n";
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
words = set(data[1 : 1 + n])
s = data[1 + n]
m = len(s)
ok = [False] * (m + 1)
ok[0] = True
for i in range(1, m + 1):
for l in range(1, min(20, i) + 1):
if ok[i - l] and s[i - l : i] in words:
ok[i] = True
break
print("YES" if ok[m] else "NO")Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
HashSet<String> dict = new HashSet<>(Arrays.asList(br.readLine().trim().split("\\s+")));
String s = br.readLine().trim();
int m = s.length();
boolean[] ok = new boolean[m + 1];
ok[0] = true;
for (int i = 1; i <= m; i++)
for (int l = 1; l <= 20 && l <= i && !ok[i]; l++)
if (ok[i - l] && dict.contains(s.substring(i - l, i))) ok[i] = true;
System.out.println(ok[m] ? "YES" : "NO");
}
}