0:00 / 0:00

Can a string be split into dictionary words? Mark each position you can reach, building on earlier marks, until you reach the end.

▼

The problem

LeetCode 139 (Medium). Given a string s and a list of dictionary words, return whether s can be split into a sequence of one or more dictionary words. A word may be used more than once.

Examples (LeetCode's own): "leetcode", ["leet", "code"] → true; "applepenapple", ["apple", "pen"] → true (apple used twice); "catsandog", ["cats", "dog", "sand", "and", "cat"] → false (cat + sand and cats + and both strand "og").

TRY IT ON LEETCODE ▶

The solution

def wordBreak(s, wordDict):
    words = set(wordDict)
    n = len(s)
    dp = [True] + [False] * n
    for i in range(1, n + 1):
        for j in range(i):
            if dp[j] and s[j:i] in words:
                dp[i] = True
                break
    return dp[n]

Transcript

Word Break. You're given a string and a list of dictionary words. Can you cut the string into pieces that are all words? Any word can be used more than once.

Take leetcode, with leet and code: leet, then code. True. Apple pen apple works too, using apple twice. But cats and og fails. Cat, then sand, leaves the last two letters stranded. Cats, then and, strands them too. False.

The naive way tries each word that fits the front, then solves the rest the same way. But the same leftovers get solved again and again. Twenty A's and a B, with the words A and double A, take nearly twenty-nine thousand calls. Thirty A's take over three and a half million.

Instead, build a bridge. Put a post at every position, from zero to n, and light the ones you can reach. Post zero is the start, so it's lit. Post i lights up if some lit post j has a word that spans from j to i.

In code: put the words in a set, and keep n plus one flags, only the first one true. For each end i, try each start j before it. If post j is lit and the slice from j to i is a word, light post i and stop looking. Finally, return the last flag.

Let's build cats and dog, with one more d. Post zero is lit. At three, cat fits: light it. At four, cats fits from zero. Five and six stay dark. At seven, sand fits from three, so we stop looking, though and would fit from four. Eight and nine stay dark. At ten, dog fits from seven. The last lamp is lit: true.

Each of the n posts tries up to n starts: n squared checks. Each check slices and hashes up to n letters, so it's n cubed time at worst. The lamps take linear space.

Lay a word, light a lamp, and walk across. That's Word Break.