Word Break

Pattern: Strings DP

medium

can[i] says whether the first i characters split into dictionary words. It is true when some word ends at position i and can[i - len(word)] is true.

The problem

Return whether s can be split into a sequence of words from wordDict (words may be reused).

Think first

  • What does the last word of a split look like?
  • What must be true before it?
  • What is can[0]?

Hints

    Brute force, and why it fails

    Try every split: 2ⁿ.

    The key insight

    Whether a prefix can be split depends only on shorter prefixes.

    Dry run

    'leetcode', words leet and code. can[0] = true; can[4] = true (leet).

    Step 1 of 2

    The plan

    can[0] = true
    for i in 1..n: can[i] = any(can[i - len(w)] and s ends with w at i for w in words)
    

    Complexity

    Time
    O(n × words × L)
    Space
    O(n)

    L is the longest word length.

    Edge cases

    • Empty string: true.
    • A word used twice.
    • No split: false.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public boolean wordBreak(String s, String[] wordDict) {
            Set<String> words = new HashSet<>(Arrays.asList(wordDict));
            int n = s.length();
            boolean[] ok = new boolean[n + 1];      // ok[i]: the first i characters can be split into words
            ok[0] = true;
            for (int i = 1; i <= n; i++)
                for (int j = 0; j < i && !ok[i]; j++)
                    if (ok[j] && words.contains(s.substring(j, i))) ok[i] = true;   // a good split, then one more word
            return ok[n];
        }
    }

    C++

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& wordDict) {
            unordered_set<string> words(wordDict.begin(), wordDict.end());
            int n = static_cast<int>(s.size());
            vector<bool> ok(n + 1, false);          // ok[i]: the first i characters can be split into words
            ok[0] = true;
            for (int i = 1; i <= n; i++)
                for (int j = 0; j < i && !ok[i]; j++)
                    if (ok[j] && words.count(s.substr(j, i - j))) ok[i] = true;   // a good split, then one more word
            return ok[n];
        }
    };

    Python

    class Solution:
        def wordBreak(self, s: str, wordDict: list[str]) -> bool:
            words = set(wordDict)
            ok = [True] + [False] * len(s)          # ok[i]: the first i characters can be split into words
            for i in range(1, len(s) + 1):
                ok[i] = any(ok[j] and s[j:i] in words for j in range(i))   # a good split, then one more word
            return ok[-1]

    Common mistakes

    • Greedy by the longest word.
    • Forgetting can[0].

    Similar problems