Approach (Dynamic Programming — End-Exclusive Prefixes with Length Bounds Optimization)
We solve the Word Break problem using Dynamic Programming (DP) over end-exclusive prefixes of the input string.
Let the input string be s and the dictionary be wordDict.
We define a boolean array dp of length m + 1 (where m = s.length) such that:
-
dp[substringExclusiveEndIndex]is true if and only if the substrings[0:substringExclusiveEndIndex](end is exclusive) can be segmented into valid dictionary words.
Initialization
-
Build a hash set
wordSetfromwordDictfor O(1) average lookup time. -
Compute the minimum and maximum word lengths in the dictionary:
•minWordLen = min(len(w))forw ∈ wordDict
•maxWordLen = max(len(w))forw ∈ wordDict
This allows us to ignore substrings that are too short or too long to match any valid word. -
Initialize the boolean array
dpwith all values set tofalse. -
Set the base case
dp[0] = true, representing that the empty string can always be segmented.
Iteration Logic
We iterate over all possible end-exclusive indices of the string that could end a valid word:
-
For each
substringExclusiveEndIndexfrommax(1, minWordLen)tom:-
Restrict the range of possible start indices using the known word length bounds:
startLowerBound = max(0, substringExclusiveEndIndex - maxWordLen)
startUpperBound = substringExclusiveEndIndex - minWordLen -
For each
substringStartIndexin[startLowerBound, startUpperBound]: ifdp[substringStartIndex] = true(meanings[0:substringStartIndex], end-exclusive, can be segmented) ands[substringStartIndex:substringExclusiveEndIndex](end-exclusive) exists inwordSet, we can also segments[0:substringExclusiveEndIndex](end-exclusive). -
Once such a substring is found, we set
dp[substringExclusiveEndIndex] = trueand skip further checks for this index.
-
Restrict the range of possible start indices using the known word length bounds:
Final Result
After completing all iterations, dp[m] (where m = s.length)
represents whether the entire string s can be segmented into valid dictionary words.
If dp[m] = true, segmentation is possible; otherwise, it is not.