Skip to main content
57

Word Break

Mediumdynamic programmingstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

Given a string s and a list of words wordDict, return true if s can be split into a sequence of one or more dictionary words, with nothing left over. Each word may be used any number of times.

Understand the problem

  • You cut s into pieces, and every piece must be a word from wordDict.
  • No letters may be left over, and you can't reorder or skip letters.
  • The same dictionary word can be used more than once.
  • You only answer yes or no; you don't need to return the split.

Example 1

text
Input:  s = "leetcode", wordDict = ["leet", "code"]
Output: true

"leet" + "code".

Example 2

text
Input:  s = "applepenapple", wordDict = ["apple", "pen"]
Output: true

"apple" + "pen" + "apple": words can repeat.

Example 3

text
Input:  s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

"cats" + "and" or "cat" + "sand" both leave "og", which isn't a word.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • All words are unique and contain lowercase English letters.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    For every position i in the string, record whether the first i characters can be split into words: they can if some dictionary word ends at i and the part before that word could also be split.

    The naive approach (and why it's slow)

    Recursion: "try every word that matches at the start, then solve the rest". The problem is that the same leftover gets solved again and again. In Example 3, "cats" + "and" and "cat" + "sand" both reach "og". On a string like "aaaa…ab" with words "a", "aa", "aaa", the number of ways to split explodes, and every one of them fails at the b. That's exponential time.

    The key insight: only the position matters

    Whether the rest of s can be split depends only on where you are, not on which words got you there. So there are only n + 1 different questions to answer, one per position. Answer each once and store it. That's dynamic programming.

    Define canBreak[i] = "the first i characters of s can be split into words":

    text
    canBreak[0] = true      (the empty prefix: nothing to split)
    canBreak[i] = true  if, for some word w:
                     s has w ending exactly at position i,  and
                     canBreak[i - w.length] is true

    In words: the last word of the split ends at i; whatever comes before it must also be splittable. Fill the table from 1 to n and return canBreak[n].

    Step by step

    s = "leetcode", wordDict = ["leet", "code"]:

    iFirst i charactersWord ending at i?canBreak[i]
    0""(base case)true
    1–3l, le, leenonefalse
    4leetleet (starts at 0, canBreak[0] ✓)true
    5–7leetc … leetcodnonefalse
    8leetcodecode (starts at 4, canBreak[4] ✓)true

    Answer: canBreak[8] = true.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With n = the length of s, W = the number of words and L = the longest word:

    • Time: O(n · W · L). For each position, try each word, and comparing a word takes up to L steps.
    • Memory: O(n) for the table.

    Common mistakes

    • Greedily taking the first (or longest) matching word. In Example 3, taking "cat" or "cats" both look fine at first. Only checking every option reveals whether some split works.
    • Off-by-one in the indexes. canBreak[i] is about the first i characters, so the table has n + 1 entries and the word ending at i starts at i - w.length.
    • Forgetting canBreak[0] = true. Without it, nothing can ever become true.

    Going deeper

    • Putting the words in a Set and checking the substrings s[j..i) for every j in the last 20 positions (the maximum word length) is an equally good way to do the inner check.
    • Word Break II asks for every possible split, not just yes or no. That needs backtracking, with this table used to skip dead ends.

    Reference solution

    js
    /**
     * @param {string} s
     * @param {string[]} wordDict
     * @return {boolean}
     */
    export default function wordBreak(s, wordDict) {
      const canBreak = new Array(s.length + 1).fill(false)
      // canBreak[i]: can the first i characters be split into words?
      canBreak[0] = true // the empty prefix needs no words
      for (let i = 1; i <= s.length; i++) {
        // Try each word as the LAST word of the split, ending exactly at position i.
        for (const word of wordDict) {
          const start = i - word.length // where that word would begin
          // It fits, the part before it can be split, and the letters really match.
          if (start >= 0 && canBreak[start] && s.startsWith(word, start)) {
            canBreak[i] = true
            break // one way is enough
          }
        }
      }
      return canBreak[s.length]
    }
    ts
    export default function wordBreak(s: string, wordDict: string[]): boolean {
      const canBreak = new Array<boolean>(s.length + 1).fill(false)
      // canBreak[i]: can the first i characters be split into words?
      canBreak[0] = true // the empty prefix needs no words
      for (let i = 1; i <= s.length; i++) {
        // Try each word as the LAST word of the split, ending exactly at position i.
        for (const word of wordDict) {
          const start = i - word.length // where that word would begin
          // It fits, the part before it can be split, and the letters really match.
          if (start >= 0 && canBreak[start] && s.startsWith(word, start)) {
            canBreak[i] = true
            break // one way is enough
          }
        }
      }
      return canBreak[s.length]
    }
    python
    def word_break(s: str, word_dict: list[str]) -> bool:
        # can_break[i]: can the first i characters be split into words?
        # can_break[0] is True: the empty prefix needs no words.
        can_break = [True] + [False] * len(s)
        for i in range(1, len(s) + 1):
            # Try each word as the LAST word of the split, ending exactly at position i.
            for word in word_dict:
                start = i - len(word)  # where that word would begin
                # It fits, the part before it can be split, and the letters really match.
                if start >= 0 and can_break[start] and s.startswith(word, start):
                    can_break[i] = True
                    break  # one way is enough
        return can_break[len(s)]