Word Break – Solution & Complexity
1. Understanding the Problem
- You are given a string
sand a list of valid wordswordDict. - You must decide if
scan be cut into pieces where every piece is a dictionary word. - Words can be reused, and you must use the whole string with no leftover characters.
2. Spotting Overlapping Subproblems
- Whether
sis breakable depends on whether some prefix is a word and the remaining suffix is also breakable. - The same suffix gets asked about repeatedly, so plain recursion does duplicated work.
- This overlap is the signal to use dynamic programming.
3. Defining the DP State
- Let
dp[i]mean "the firsticharacterss[0:i]can be segmented". dp[0]isTruebecause the empty string is trivially segmentable.- The answer we want is
dp[len(s)].
4. Filling the Table
- For each end position
i, look at every split pointj < i. - If
dp[j]isTrueand the slices[j:i]is a dictionary word, thendp[i]is reachable. - Once we find one valid split we can stop scanning that
i.
5. Complexity
- Time:
O(n^2)for the nested loops, times the slice/hash cost. - Space:
O(n)for thedparray plus the word set. - This comfortably handles the constraints for the Word Break problem.