Visualize

Pattern visualizer

Word Break

The insight: once you know a shorter prefix of the string can already be broken into valid words, you don't need to re-decide it — you only need to check whether what's left after that break point is itself one whole dictionary word. dp[i] tracks exactly that: "can the first i characters be segmented?", built left to right by checking every earlier breakable prefix j and testing if the remaining chunk s[j:i] is in the dictionary. The base case dp[0] = true (an empty prefix is trivially breakable) is what lets the very first real word get recognized, and the final answer is simply dp[n] — can the whole string be broken this way. Animated on: s="leetcode", wordDict=["leet","code"].

Dynamic Programming

time O(n^2)space O(n)step 1 / 8
1
[0]
0
[1]
0
[2]
0
[3]
0
[4]
0
[5]
0
[6]
0
[7]
0
[8]
line 4

Initialize dp[0] = true, base case: empty string can always be segmented

Pseudocode
1FUNCTION wordBreak(s, wordDict):
2 n = the length of s
3 dp = a list of n+1 falses (dp[i] = can first i chars be segmented)
4 dp[0] = true (an empty prefix is always breakable)
5 FOR i from 1 to n:
6 FOR j from 0 to i-1:
7 IF dp[j] is true and the substring s[j..i] is in wordDict:
8 dp[i] = true
9 stop this inner loop
10 RETURN dp[n]

← / → step · space play · Home restart

Where to practice Dynamic Programming