AAI Agentic Handbook
Problem 54 · Dynamic Programming

Word Break

MediumClassic DSA & systems
01Problem

Given a string s and a dictionary of words, return whether s can be segmented into a sequence of one or more dictionary words.

02Key insight

dp[i] is true if some dictionary word ends at i and dp[start] is true. Bound the inner loop by the longest dictionary word to avoid O(n^2) substring checks.

03Solution

Try it first.

TimeO(n * L * L)
SpaceO(n)
tests.py · 4 passing
tests.pypython4 lines
assert word_break("leetcode", ["leet","code"]) is True
assert word_break("catsandog", ["cats","dog","sand","and","cat"]) is False
assert word_break("", ["a"]) is True
assert word_break("aaab", ["a","aa"]) is False
04Staff-level follow-up

Tokenizing user queries at scale? Use a trie (or Aho-Corasick) to walk all dictionary matches from each start in one pass, and score segmentations with word frequencies (Viterbi) instead of a boolean.