Boss lesson · Unit 04
Spot the DP
Word break, and telling DP problems from greedy ones
What you practise
- Word break
- Telling DP from greedy
Try a question from this lesson
Pick one
Allowed words: cat, cats, and, sand. Words may be reused. Can "catsand" be cut into allowed words?
Correct answer
Yes, in two ways
Why
cat + sand and cats + and both work. The first cut is a real choice: after "cat" or after "cats". Here both lead somewhere, but in general you cannot know which first word is right until you try the rest.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Word break
You get a string with no spaces and a set of allowed words. Can the string be cut into allowed words? Words may be reused.
"applepie" with apple and pie: yes. "applepies": no, an s is left over.
Scanning left to right and grabbing a word whenever you see one sounds like enough. It is not, and seeing why is the point of this lesson.
Concept
A table of cut points
ok[i] answers the question for the first i characters. The empty prefix is trivially fine, so ok[0] is true.
For each i, try every earlier cut point j. If the part before j works and the piece from j to i is an allowed word, the first i characters work too.
def word_break(s, words):
ok = [True] + [False] * len(s)
for i in range(1, len(s) + 1):
for j in range(i):
part = s[j:i]
if ok[j] and part in words:
ok[i] = True
return ok[-1]function wordBreak(s, words) {
const ok = [true];
for (let i = 1; i <= s.length; i++) {
ok[i] = false;
for (let j = 0; j < i; j++) {
const part = s.slice(j, i);
if (ok[j] && words.has(part)) {
ok[i] = true;
}
}
}
return ok[s.length];
}function wordBreak(
s: string,
words: Set<string>,
): boolean {
const ok = [true];
for (let i = 1; i <= s.length; i++) {
ok[i] = false;
for (let j = 0; j < i; j++) {
const part = s.slice(j, i);
if (ok[j] && words.has(part)) {
ok[i] = true;
}
}
}
return ok[s.length];
}Python notePass the words as a set, such as {"apple", "pie"}, so that part in words is an O(1) lookup and not a scan.
JavaScript notewords is a Set. Its has method is the fast membership test; s.slice(j, i) is the piece from j up to, not including, i.
TypeScript noteSet<string> is a set whose members are strings. const ok = [true] is inferred as boolean[].
10 more exercises in the app
- 5× multiple choice
- 1× fill the blanks
- 2× type the answer
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.