15% off all plans & roadmaps Use code
See plansLeetCode 140 · Solution & editorial
Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Word Break II is a Dynamic Programming (DP) Patterns problem, in the 1D Array (Word Break Style) subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
Determine if string can be segmented into dictionary words using DP.
The reference solution runs in O(2^n * n) time and O(2^n * n) space.
Word Break II has been reported in interviews at Facebook, Amazon, Bloomberg, ByteDance, Google, Microsoft.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Word Break II is a Dynamic Programming (DP) Patterns problem, in the 1D Array (Word Break Style) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.