Word Break

Can the string be segmented into dictionary words?

Pattern

String DP

This problem follows the String DP pattern, commonly found in the 1-D Dynamic Programming category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

dp[i] = true if s[0..j] is valid and s[j..i] is in dictionary, for some j.

Key Insight

dp[i] means 'can s[0:i] be segmented?' — you try every possible last word s[j:i] and check if the prefix s[0:j] was also valid.

Step-by-step

  1. 1Create dp array of size (n + 1), dp[0] = true
  2. 2For each position i from 1 to n:
  3. 3Check every possible word ending at position i
  4. 4If dp[j] is true and s[j:i] is in the dictionary, set dp[i] = true

Pseudocode

dp = [false] * (len(s) + 1)
dp[0] = true
wordSet = set(wordDict)
for i in range(1, len(s) + 1):
    for j in range(i):
        if dp[j] and s[j:i] in wordSet:
            dp[i] = true
            break
return dp[len(s)]
Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(n)
More 1-D Dynamic Programming Problems

Master this pattern with YeetCode

Practice Word Break and similar 1-D Dynamic Programming problems with flashcards. Build pattern recognition through active recall.

Practice this problem