← Back to Algorithms, page 5

algorithms-0083 · Medium mid

Word break: decide whether a string can be split into a sequence of dictionary words, and list every possible sentence when asked.

Let ok[i] mean the prefix of length i can be split. Then ok[0] is True and ok[i] is True if some ok[j] is True and s[j:i] is a dictionary word. Limiting j to the last L positions, where L is the longest word, gives O(n * L) substring checks. Listing all sentences needs memoized recursion over start positions, and the output itself can be exponential.

Full answer

Problem

Given a string s and a list of words, return True if s can be segmented into one or more dictionary words (words may repeat). Follow-up: return all such segmentations as space-separated sentences.

Example: "leetcode" with ["leet", "code"] is True; "catsandog" with ["cats", "dog", "sand", "and", "cat"] is False; "catsanddog" has two sentences: "cat sand dog" and "cats and dog".

Constraints: 1 <= len(s) <= 300, up to 1,000 words of length up to 20.

Brute force

Try every word as a prefix and recurse on the rest. Without memoization a string like "aaaa...ab" with words "a", "aa", "aaa" causes exponential work, because the same suffix is retried along many paths.

Optimal approach

  1. Put words in a set; let L be the longest word length.
  2. ok = [True] + [False] * n.
  3. For i from 1 to n, for j from max(0, i - L) to i - 1: if ok[j] and s[j:i] is in the set, set ok[i] = True and stop scanning j.
  4. Return ok[n].

All sentences: memoize go(i) = list of sentences for s[i:], trying each end j where s[i:j] is a word.

Why it works

A valid split of the first i characters has a last word s[j:i], and the part before it must itself be a valid split, which is ok[j]. Checking all j covers every possible last word; words longer than L cannot match, so the restricted range loses nothing. Memoizing by start index in the listing version means each suffix's sentences are built once.

Complexity

Decision: O(n * L) set lookups, each hashing a substring of length up to L, so O(n * L^2) character work in the worst case; O(n) space. A trie walk from each start position avoids rebuilding substrings. Listing: output-sensitive and exponential in the worst case.

Code

python
import random
from functools import lru_cache


def word_break(s, words):
    """Can s be split into dictionary words? dp[i] = some j < i with dp[j] and s[j:i] in words.
    Only look back as far as the longest word: O(n * L) substring checks."""
    wordset = set(words)
    if not wordset:
        return s == ""
    longest = max(map(len, wordset))
    ok = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        for j in range(max(0, i - longest), i):
            if ok[j] and s[j:i] in wordset:
                ok[i] = True
                break
    return ok[-1]


def word_break_all(s, words):
    """Every sentence (can be exponential in count); memoised by start index."""
    wordset = set(words)

    @lru_cache(maxsize=None)
    def go(i):
        if i == len(s):
            return [""]
        out = []
        for j in range(i + 1, len(s) + 1):
            if s[i:j] in wordset:
                out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
        return out
    return sorted(go(0))


def brute(s, words):
    """Try every prefix recursively, no memo: exponential."""
    if s == "":
        return True
    return any(s.startswith(w) and brute(s[len(w):], words) for w in words if w)


if __name__ == "__main__":
    assert word_break("leetcode", ["leet", "code"])
    assert word_break("applepenapple", ["apple", "pen"])
    assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])
    assert word_break("", ["a"]) and not word_break("a", [])
    assert word_break_all("catsanddog", ["cat", "cats", "and", "sand", "dog"]) == ["cat sand dog", "cats and dog"]
    rng = random.Random(83)
    for _ in range(1000):
        words = list({"".join(rng.choice("ab") for _ in range(rng.randint(1, 3))) for _ in range(rng.randint(0, 4))})
        s = "".join(rng.choice("ab") for _ in range(rng.randint(0, 10)))
        assert word_break(s, words) == brute(s, words) == bool(word_break_all(s, words))
    print("all tests passed")

Save as b83_word_break.py and run python3 b83_word_break.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty string (True: zero words). Empty dictionary. A word that is a prefix of another (cat, cats). Repeated words. Very long strings with short words (L keeps the inner loop short).

Pattern

Prefix segmentation DP: "can prefix i be completed from some earlier valid point". Related: palindrome partitioning (minimum cuts), decode ways, concatenated words, and sentence segmentation for languages written without spaces.

python
import random
from functools import lru_cache


def word_break(s, words):
    """Can s be split into dictionary words? dp[i] = some j < i with dp[j] and s[j:i] in words.
    Only look back as far as the longest word: O(n * L) substring checks."""
    wordset = set(words)
    if not wordset:
        return s == ""
    longest = max(map(len, wordset))
    ok = [True] + [False] * len(s)
    for i in range(1, len(s) + 1):
        for j in range(max(0, i - longest), i):
            if ok[j] and s[j:i] in wordset:
                ok[i] = True
                break
    return ok[-1]


def word_break_all(s, words):
    """Every sentence (can be exponential in count); memoised by start index."""
    wordset = set(words)

    @lru_cache(maxsize=None)
    def go(i):
        if i == len(s):
            return [""]
        out = []
        for j in range(i + 1, len(s) + 1):
            if s[i:j] in wordset:
                out += [s[i:j] + (" " + rest if rest else "") for rest in go(j)]
        return out
    return sorted(go(0))


def brute(s, words):
    """Try every prefix recursively, no memo: exponential."""
    if s == "":
        return True
    return any(s.startswith(w) and brute(s[len(w):], words) for w in words if w)


if __name__ == "__main__":
    assert word_break("leetcode", ["leet", "code"])
    assert word_break("applepenapple", ["apple", "pen"])
    assert not word_break("catsandog", ["cats", "dog", "sand", "and", "cat"])
    assert word_break("", ["a"]) and not word_break("a", [])
    assert word_break_all("catsanddog", ["cat", "cats", "and", "sand", "dog"]) == ["cat sand dog", "cats and dog"]
    rng = random.Random(83)
    for _ in range(1000):
        words = list({"".join(rng.choice("ab") for _ in range(rng.randint(1, 3))) for _ in range(rng.randint(0, 4))})
        s = "".join(rng.choice("ab") for _ in range(rng.randint(0, 10)))
        assert word_break(s, words) == brute(s, words) == bool(word_break_all(s, words))
    print("all tests passed")

Boolean prefix DP bounded by the longest word and a memoized sentence lister, cross-checked against plain recursion on random strings and dictionaries.

Complexity

Time: O(n * L) lookups. Space: O(n). Each lookup hashes a substring of up to L characters; a trie avoids building substrings. Listing all sentences is output-sensitive.

By level

Fresher: Writes the boolean prefix table with a set of words and traces it on a short example. Explains why greedy longest match fails.

Mid: Bounds the inner loop by the longest word, writes the memoized sentence lister, and discusses output size. Uses a trie to avoid substring building.

Senior: Discusses segmentation for search queries and languages without spaces, ranking splits with word frequencies, and memory for large dictionaries. Evaluates trie versus hashing for lookup speed.

Key points

  • ok[i] true if some ok[j] and s[j:i] is a word
  • Limit j by the longest word
  • Use a set (or trie) for lookups
  • Memoize by start index for the listing version
  • Listing output can be exponential

Common mistakes

  • Greedy longest-match splitting
  • Recursion without memoization
  • Checking all j without the L bound on long strings
  • Forgetting that words may repeat

Follow-ups

  • How would you find the split with the fewest words?
  • How would a trie speed this up?
  • How would you handle a dictionary of millions of words?

Tips

  • Show why greedy matching fails
  • Explain the L bound
  • Mention exponential output for the listing version

Evaluation rubric

  • Correct DP
  • Uses a set
  • Correct complexity
  • Handles the listing follow-up