CodingNodes / 1-D Dynamic Programming / Word Break System design Space play · ←→ step · R restart

Problem

You get a string s and a list of dictionary words. Decide whether s can be cut into pieces so that every piece is a word from the list.

A word may be used any number of times, or not at all. Return true if such a cut exists.

Constraints

  • 1 ≤ s.length ≤ 10
  • 1 ≤ wordDict.length ≤ 6
  • Each word has 1 to 8 lowercase letters

Examples: pick one to animate

Solutions

TimeO(n²) SpaceO(n + words)

Time: Each prefix tries every cut point before it, with one set lookup per cut.

Space: The dp array holds n + 1 flags, plus the set of words.

dp[i] says whether the first i letters can be split into words. For each i, try every cut j: if dp[j] is true and the piece s[j:i] is a word, then dp[i] is true.