You are given a string s and a list of words, wordDict. Decide whether s can be cut into pieces so that every piece is a word from the list, with nothing left over.
A word may be used as many times as you like, and not every word has to be used. Return true if such a cut exists, false if not.
Example 1
Input: s = "icecream", wordDict = ["ice", "cream"] Output: true Why: "ice" + "cream"
2 more examples and the constraints
Example 2
Input: s = "redbluered", wordDict = ["red", "blue"] Output: true Why: "red" + "blue" + "red", reusing "red"
Example 3
Input: s = "moonbeam", wordDict = ["moon", "mo", "on", "bean"] Output: false Why: "moon" or "mo" + "on" both leave "beam", which is no word
Constraints
- 1 ≤ length of s ≤ 300
- 1 ≤ number of words ≤ 1,000, each 1 to 20 letters long
- s and the words use only lower-case English letters
- The words are all different
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion + memoO(n² · m)
- Bottom-up DPO(n² · m)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 300-letter string | Verdict |
|---|---|---|---|
| Recursion + memo | O(n² · m) | Passes; recursion overhead | |
| Bottom-up DP | O(n² · m) | Best; simple loops, no recursion |
n = length of s, m = longest word, w = total letters in the dictionary.
Edge cases to test
- Reusing a word. "redbluered" needs "red" twice; the dictionary is not used up.
- Greedy longest word fails. "carsand" with cars, car, sand: taking "cars" first leaves "and", so every start must be tried.
- Almost splits. "moonbeam" splits up to "moon" but "beam" is not a word, so the answer is false.
- Many overlapping words. 299 a's and a b with words a, aa, …: without memo or table this is exponential.
Common mistakes
- Matching the longest word first and never backing up, which fails "carsand".
- Forgetting ok[0] = True, so nothing can ever be split.
- Plain recursion without a memo: correct, but it times out on long runs of the same letter.
How to talk through it
- 1Clarify. Can a word be used more than once? Do all words have to be used? Can s be empty?
- 2Give the recursion. Try every first word and recurse on the rest; say it repeats the same leftovers and is exponential.
- 3Add the memo. The answer only depends on where the leftover starts, so there are n distinct questions.
- 4Code the table. ok[i] is True when some ok[j] is True and s[j:i] is a word; mention the 20-letter cap on j.
- 5Test out loud. Run "carsand" and the long run of a's with a b at the end before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?