Skip to content
StackDecode
Dynamic programmingAnimated

Word Break

Can the string be split into dictionary words?

Time

O(n²)

Extra space

O(n)

Use it for

Tokenising text without spaces.

How it works

  1. Can the string be split into words from the dictionary?
  2. ok[i] = "the first i letters can be split". ok[0] is true (nothing needed).
  3. For each i, look for a position j < i where ok[j] is true and the piece s[j..i) is a dictionary word.
  4. ok[n] is the answer. O(n²).

Watch it run

Loading animation…