Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] Output: ["cats and dog","cat sand dog"]
Example 2:
Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"] Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: []
Constraints:
1 <= s.length <= 201 <= wordDict.length <= 10001 <= wordDict[i].length <= 10s and wordDict[i] consist of only lowercase English letters.wordDict are unique.Problem summary: 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. Note that the same word in the dictionary may be reused multiple times in the segmentation.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming · Backtracking · Trie
"catsanddog" ["cat","cats","and","sand","dog"]
"pineapplepenapple" ["apple","pen","applepen","pine","pineapple"]
"catsandog" ["cats","dog","sand","and","cat"]
word-break)concatenated-words)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #140: Word Break II
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;
void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
boolean search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return false;
}
node = node.children[c];
}
return node.isEnd;
}
}
class Solution {
private Trie trie = new Trie();
public List<String> wordBreak(String s, List<String> wordDict) {
for (String w : wordDict) {
trie.insert(w);
}
List<List<String>> res = dfs(s);
return res.stream().map(e -> String.join(" ", e)).collect(Collectors.toList());
}
private List<List<String>> dfs(String s) {
List<List<String>> res = new ArrayList<>();
if ("".equals(s)) {
res.add(new ArrayList<>());
return res;
}
for (int i = 1; i <= s.length(); ++i) {
if (trie.search(s.substring(0, i))) {
for (List<String> v : dfs(s.substring(i))) {
v.add(0, s.substring(0, i));
res.add(v);
}
}
}
return res;
}
}
// Accepted solution for LeetCode #140: Word Break II
type Trie struct {
children [26]*Trie
isEnd bool
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func (this *Trie) search(word string) bool {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
return false
}
node = node.children[c]
}
return node.isEnd
}
func wordBreak(s string, wordDict []string) []string {
trie := newTrie()
for _, w := range wordDict {
trie.insert(w)
}
var dfs func(string) [][]string
dfs = func(s string) [][]string {
res := [][]string{}
if len(s) == 0 {
res = append(res, []string{})
return res
}
for i := 1; i <= len(s); i++ {
if trie.search(s[:i]) {
for _, v := range dfs(s[i:]) {
v = append([]string{s[:i]}, v...)
res = append(res, v)
}
}
}
return res
}
res := dfs(s)
ans := []string{}
for _, v := range res {
ans = append(ans, strings.Join(v, " "))
}
return ans
}
# Accepted solution for LeetCode #140: Word Break II
class Trie:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
def search(self, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
return False
node = node.children[idx]
return node.is_end
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def dfs(s):
if not s:
return [[]]
res = []
for i in range(1, len(s) + 1):
if trie.search(s[:i]):
for v in dfs(s[i:]):
res.append([s[:i]] + v)
return res
trie = Trie()
for w in wordDict:
trie.insert(w)
ans = dfs(s)
return [' '.join(v) for v in ans]
// Accepted solution for LeetCode #140: Word Break II
struct Solution;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::hash::Hasher;
impl Solution {
fn word_break(s: String, word_dict: Vec<String>) -> Vec<String> {
let n = s.len();
let mut dict: HashSet<u64> = HashSet::new();
let mut alphabet: Vec<bool> = vec![false; 256];
for word in word_dict {
let mut hasher = DefaultHasher::new();
for b in word.bytes() {
alphabet[b as usize] = true;
hasher.write_u8(b);
}
dict.insert(hasher.finish());
}
let s: Vec<u8> = s.bytes().collect();
for i in 0..n {
if !alphabet[s[i] as usize] {
return vec![];
}
}
let mut cur = vec![];
let mut res = vec![];
Self::dfs(0, &mut cur, &mut res, &dict, &s, n);
res
}
fn dfs(
start: usize,
cur: &mut Vec<(usize, usize)>,
all: &mut Vec<String>,
dict: &HashSet<u64>,
s: &[u8],
n: usize,
) {
if start == n {
let mut words = vec![];
for &(l, r) in cur.iter() {
let mut word = "".to_string();
for i in l..=r {
word.push(s[i] as char);
}
words.push(word);
}
all.push(words.join(" "));
}
let mut hasher = DefaultHasher::new();
for i in start..n {
hasher.write_u8(s[i]);
if dict.contains(&hasher.finish()) {
cur.push((start, i));
Self::dfs(i + 1, cur, all, dict, s, n);
cur.pop();
}
}
}
}
#[test]
fn test() {
let s = "catsanddog".to_string();
let word_dict = vec_string!["cat", "cats", "and", "sand", "dog"];
let mut res = vec_string!["cats and dog", "cat sand dog"];
let mut ans = Solution::word_break(s, word_dict);
res.sort();
ans.sort();
assert_eq!(ans, res);
let s = "pineapplepenapple".to_string();
let word_dict = vec_string!["apple", "pen", "applepen", "pine", "pineapple"];
let mut res = vec_string![
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
];
let mut ans = Solution::word_break(s, word_dict);
res.sort();
ans.sort();
assert_eq!(ans, res);
let s = "catsandog".to_string();
let word_dict = vec_string!["cats", "dog", "sand", "and", "cat"];
let mut res = vec_string![];
let mut ans = Solution::word_break(s, word_dict);
res.sort();
ans.sort();
assert_eq!(ans, res);
}
// Accepted solution for LeetCode #140: Word Break II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #140: Word Break II
// class Trie {
// Trie[] children = new Trie[26];
// boolean isEnd;
//
// void insert(String word) {
// Trie node = this;
// for (char c : word.toCharArray()) {
// c -= 'a';
// if (node.children[c] == null) {
// node.children[c] = new Trie();
// }
// node = node.children[c];
// }
// node.isEnd = true;
// }
//
// boolean search(String word) {
// Trie node = this;
// for (char c : word.toCharArray()) {
// c -= 'a';
// if (node.children[c] == null) {
// return false;
// }
// node = node.children[c];
// }
// return node.isEnd;
// }
// }
//
// class Solution {
// private Trie trie = new Trie();
//
// public List<String> wordBreak(String s, List<String> wordDict) {
// for (String w : wordDict) {
// trie.insert(w);
// }
// List<List<String>> res = dfs(s);
// return res.stream().map(e -> String.join(" ", e)).collect(Collectors.toList());
// }
//
// private List<List<String>> dfs(String s) {
// List<List<String>> res = new ArrayList<>();
// if ("".equals(s)) {
// res.add(new ArrayList<>());
// return res;
// }
// for (int i = 1; i <= s.length(); ++i) {
// if (trie.search(s.substring(0, i))) {
// for (List<String> v : dfs(s.substring(i))) {
// v.add(0, s.substring(0, i));
// res.add(v);
// }
// }
// }
// return res;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.