Word Break Problem | (Trie solution)

Pattern: Word counting

medium

can[i] says whether the first i characters split into dictionary words. From every reachable i, walk the trie along s; every word end met at position j makes can[j + 1] true.

The problem

Return whether s can be split into a sequence of dictionary words (words may repeat). Use a trie to find the words starting at each position.

Think first

  • What does the trie replace?
  • From which positions should a walk start?
  • When does a walk stop?

Hints

    Brute force, and why it fails

    Try every split: exponential. A hash-set DP is O(n² × L).

    The key insight

    One trie walk from a start finds every dictionary word beginning there, with no substring copies.

    Dry run

    s = ilike. can[0]: walk i: a word: can[1].

    Step 1 of 2

    The plan

    insert all words; can[0] = true
    for i with can[i]: node = root
      for j from i: node = child(s[j]) or stop; if node ends a word: can[j + 1] = true
    

    Complexity

    Time
    O(n × L)
    Space
    O(n + total letters)

    L is the longest word length.

    Edge cases

    • No split: false.
    • A word used many times.
    • s shorter than every word.
    I've built my logic, show the code

    Java

    class Solution {
        private static class Node {
            Node[] next = new Node[26];
            boolean end;
        }
    
        public boolean wordBreak(String s, String[] dictionary) {
            Node root = new Node();
            for (String w : dictionary) {
                Node n = root;
                for (char c : w.toCharArray()) {
                    if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
                    n = n.next[c - 'a'];
                }
                n.end = true;
            }
            int len = s.length();
            boolean[] can = new boolean[len + 1];   // can[i]: s[0..i-1] splits into words
            can[0] = true;
            for (int i = 0; i < len; i++) {
                if (!can[i]) continue;
                Node n = root;
                for (int j = i; j < len; j++) {     // every word starting at i, read off one trie walk
                    n = n.next[s.charAt(j) - 'a'];
                    if (n == null) break;
                    if (n.end) can[j + 1] = true;
                }
            }
            return can[len];
        }
    }

    C++

    class Solution {
    public:
        bool wordBreak(string s, vector<string>& dictionary) {
            vector<vector<int>> next(1, vector<int>(26, 0));
            vector<bool> isEnd(1, false);
            for (const string& w : dictionary) {
                int n = 0;
                for (char c : w) {
                    if (next[n][c - 'a'] == 0) {
                        next[n][c - 'a'] = static_cast<int>(next.size());
                        next.push_back(vector<int>(26, 0));
                        isEnd.push_back(false);
                    }
                    n = next[n][c - 'a'];
                }
                isEnd[n] = true;
            }
            int len = static_cast<int>(s.size());
            vector<bool> can(len + 1, false);       // can[i]: s[0..i-1] splits into words
            can[0] = true;
            for (int i = 0; i < len; i++) {
                if (!can[i]) continue;
                int n = 0;
                for (int j = i; j < len; j++) {     // every word starting at i, read off one trie walk
                    n = next[n][s[j] - 'a'];
                    if (n == 0) break;
                    if (isEnd[n]) can[j + 1] = true;
                }
            }
            return can[len];
        }
    };

    Python

    class Solution:
        def wordBreak(self, s: str, dictionary: list[str]) -> bool:
            root = {}
            for w in dictionary:
                node = root
                for c in w:
                    node = node.setdefault(c, {})
                node["$"] = True
            can = [True] + [False] * len(s)         # can[i]: s[:i] splits into words
            for i in range(len(s)):
                if not can[i]:
                    continue
                node = root
                for j in range(i, len(s)):          # every word starting at i, read off one trie walk
                    node = node.get(s[j])
                    if node is None:
                        break
                    if "$" in node:
                        can[j + 1] = True
            return can[-1]

    Common mistakes

    • Starting walks from unreachable positions.
    • Stopping at the first word found.

    Similar problems