Tensorum
LeetCode 140 · String DP / Word Break

Word Break II

LeetCode 140 · Hard · solution, intuition & step-by-step walkthrough

Backtracking over prefix words; a full path is one sentence.

HardArrayHash TableStringDynamic ProgrammingBacktracking
0 msruntime · beats 100%
19.1 MBmemory · beats 93%
1approach
8accepted runs · last 4 Mar 2026

This is how I solved Word Break II (LeetCode 140), a hard problem from the String DP / Word Break pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

We need every sentence, not just a yes/no, so explore: try each dictionary word that starts at the current position, add it to the path, recurse on the rest, and undo. Reaching the end of the string records one sentence.

Approach

  1. 1

    Dictionary in a set.

  2. 2

    backtrack(start, path): if start == len(s), join the path into a sentence.

  3. 3

    For each end after start, if s[start:end] is a word, append it, recurse from end, then pop.

  4. 4

    Return all collected sentences.

How I solved it

BacktrackingPythonexponential in the worst case
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        #if prefix exists in dict we should move forward to find the rest
        #if cat exists - check if sanddog - sand->dog
        #backrack - if cats exists - anddog - and->dog
        res=[]
        words_set = set(wordDict)
        def backtrack(start, path):
            if start == len(s):
                res.append(" ".join(path))
                return
            for end in range(start+1,len(s)+1):
                prefix = s[start:end]
                if prefix in words_set:
                    path.append(prefix)
                    backtrack(end,path)
                    path.pop()
        backtrack(0,[])
        return res

Loading the step-through…

Word Break II — FAQ

What is the intuition behind Word Break II?

We need every sentence, not just a yes/no, so explore: try each dictionary word that starts at the current position, add it to the path, recurse on the rest, and undo. Reaching the end of the string records one sentence.

How do you solve Word Break II (LeetCode 140)?

1. Dictionary in a set. 2. backtrack(start, path): if start == len(s), join the path into a sentence. 3. For each end after start, if s[start:end] is a word, append it, recurse from end, then pop. 4. Return all collected sentences.

What is the time and space complexity of Word Break II?

Time: O(2ⁿ) worst case (output can be exponential). Space: O(n) recursion. (Accepted approach: Backtracking.)

What are common mistakes in Word Break II?

Pop after recursing or later sentences inherit stale words. For heavy inputs, memoising sentences per start index avoids rework.