You get a string s with no spaces and a list of distinct words wordDict. Insert spaces into s so that every piece is a word from the list. A word may be used as many times as you like.
Return every sentence you can build this way, in any order. If s cannot be split, return an empty list.
Example 1
Input: s = "sunflowerpot", wordDict = ["sun", "flower", "sunflower", "pot", "flowerpot"] Output: ["sun flower pot", "sun flowerpot", "sunflower pot"] Why: three ways cut the string into listed words
2 more examples and the constraints
Example 2
Input: s = "bookkeeper", wordDict = ["book", "keep", "keeper", "bookkeeper", "er"] Output: ["book keep er", "book keeper", "bookkeeper"] Why: "keeper" can also be "keep" + "er"
Example 3
Input: s = "dogcatx", wordDict = ["dog", "cat", "dogcat"] Output: [] Why: no word ends with the final x
Constraints
- s has between 1 and 20 letters
- wordDict holds between 1 and 1,000 distinct words, each 1 to 10 letters long
- Only lowercase English letters appear
- The answer holds at most 100,000 sentences
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BacktrackingO(2ⁿ)
- Memoized suffixesO(n² + output)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for "aaaa…ab" (20 letters, no answer) | Verdict |
|---|---|---|---|
| Backtracking | O(2ⁿ · n) | Passes; re-searches dead ends | |
| Memoized suffixes | O(n² + output) | Best; each suffix once |
n = length of s (at most 20); output = total length of all sentences returned.
Edge cases to test
- No split exists. "dogcatx" returns an empty list, not a list with an empty string.
- A word used twice. "abab" with ["ab"] gives "ab ab"; words are not used up.
- The whole string is one word. Return it alone as a sentence with no spaces.
- Long dead end. 19 a's and a b: no answer, and only the memo stops the search from exploding.
Common mistakes
- Returning [] instead of [""] at the end of the string, which makes every sentence disappear.
- Adding a trailing space when the rest of the sentence is empty.
- Searching the word list with a loop instead of a set, which multiplies the work by up to 1,000.
How to talk through it
- 1Clarify. Can a word be reused? Do you want every sentence or just whether one exists? Any order?
- 2Give the simple version. Backtrack: try each word that starts at the current index and recurse on the rest.
- 3Spot the repeats. Different cuts reach the same suffix, so the sentences for a suffix can be cached.
- 4Code the memo. dfs(start) returns a list; the base returns [""]; prepend the word to each sentence from dfs(end).
- 5Test out loud. Run Example 1, a string with no split, and a word used twice.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?