Word Break
Question (LC.139)
Given a non-empty string and a dictionary of words, determine if the string can be segmented into a sequence of words.
Example
I: "helloworld", ["hello", "world"]
O: true
I: "hellow", ["hello", "world"]
O: falseBrute Force Search
This is a doability question (can be reframed as an optimizaiton problem)
Overlapping subproblems - [__][_][_][___]_____
Start from start find a word then keep search, we can clearly see some subtrees can be the same
Single Sequence DP
1. Define optimal subproblem
BK[n] = is [0:n] a separatable string
2. Solve by prefix
for i from 0 to n-1
if BK[i] and dict.contains(S[i:n])
BK[n] = true
otherwise by default BK[n] = false
remember array index is 1 behind dp index
3. Base case
BK[0] = true
4. Topo order
for i from 1 to n
5. Final answer
return BK[n]Time & Space Complexity
Time right now is O(n^2). We can improve the performance by adding a break statement once BK[i] is set to true. And get the maximum word length in the preprocessing and add an additional check in the inner loop. Space complexity needs to be linear since the dependencies are all of the previous subproblems.
Follow Up (LC.140)
Instead of checking the breakability, we want to return a list of strings on all the possibles ways to segment the input string.
Example
Memoized Search
Code
Time Complexity
O(len(wordDict) ^ len(n / minWordLength))
Last updated