C++ 0140.cpp
class Solution {
unordered_set<string> dict;
vector<string> result;
void dp(string s, string previous)
{
if (s.empty())
{
if (previous.empty())
return;
if (previous.back() == ' ')
previous.erase(previous.end() - 1);
result.push_back(previous);
return;
}
string word;
while (!s.empty())
{
word += s[0];
s.erase(0, 1);
if (dict.count(word) == 0)
continue;
dp(s, previous + word + ' ');
}
}
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
dict.clear();
for (auto w : wordDict)
dict.insert(w);
result.clear();
dp(s, "");
return result;
}
};
Difficulty
and has an acceptance rate of about 56% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Dynamic Programming
- Hash Table
- Memoization
- String
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation solves the classic word-break problem by enumerating every possible segmentation of an input string s that can be formed using a supplied dictionary wordDict. The core algorithm is a depth-first recursion that progressively consumes characters from s, builds candidate words, and backtracks whenever a partial word is not present in the dictionary. Valid segmentations are collected in a vector of strings and returned to the caller.
Data Structures
The class maintains two member containers.
unordered_set<string> dict;
vector<string> result;
dict stores the dictionary words in an unordered_set, providing constant-time membership tests. result accumulates the final sentences that satisfy the word-break condition.
Dictionary Initialization
Before the recursive search begins, the public method wordBreak clears any previous state, inserts each word from wordDict into dict, and resets result.
dict.clear();
for (auto w : wordDict)
dict.insert(w);
result.clear();
This step guarantees that the lookup structure reflects exactly the words supplied for the current invocation.
Recursive Exploration
The heart of the solution resides in the private method dp. It receives two parameters: the remaining suffix s that still needs to be processed, and the partially built sentence previous.
void dp(string s, string previous)
{
if (s.empty())
{
if (previous.empty())
return;
if (previous.back() == ' ')
previous.erase(previous.end() - 1);
result.push_back(previous);
return;
}
string word;
while (!s.empty())
{
word += s[0];
s.erase(0, 1);
if (dict.count(word) == 0)
continue;
dp(s, previous + word + ' ');
}
}
The function first checks whether the suffix s is empty. If it is, the current previous string represents a complete segmentation. A trailing space, if present, is removed before the sentence is stored in result. This handling of the trailing space ensures that the output sentences contain no extraneous whitespace.
When s is not empty, the method iteratively extracts a prefix character by character, appending it to a temporary word. After each character addition, the code tests whether word exists in dict. Only when the prefix forms a valid dictionary entry does the recursion continue, passing the remaining suffix s and the updated sentence previous + word + ' '.
Edge Cases Handled
The algorithm explicitly addresses several boundary conditions.
When the original input string is empty, the initial call to dp receives an empty s. The early return path detects that previous is also empty and exits without adding any entry to result.
If the input string can be segmented only by a single dictionary word, the recursion reaches the base case with previous containing that word followed by a space. The trailing-space removal logic trims the final space before the sentence is recorded.
During the iterative prefix construction, any prefix that does not belong to the dictionary is ignored via the continue statement, preventing unnecessary recursive calls on invalid paths.
The use of unordered_set::count to test membership ensures that duplicate dictionary entries do not affect the correctness of the search, as the set automatically eliminates redundancy.
Performance Optimizations
The choice of unordered_set for dict is a primary optimization. Membership checks (dict.count(word)) execute in average constant time, allowing the recursion to prune invalid prefixes quickly without scanning the entire dictionary.
The recursion only proceeds when a valid word is identified, which reduces the total number of recursive invocations compared to a naïve approach that would explore every possible split regardless of dictionary membership.
By erasing the processed character from s (s.erase(0, 1)) after each iteration, the algorithm maintains a shrinking suffix, ensuring that each recursive call works with a strictly smaller string. This property guarantees progress toward the base case and avoids revisiting already examined characters.
The final trimming of a trailing space (previous.erase(previous.end() - 1)) is performed only once per successful segmentation, avoiding repeated string manipulation during the recursive descent.
Collecting results in a pre-allocated vector<string> (result) avoids the overhead of dynamic container creation for each found sentence. The vector grows only as needed, and each push operation stores a fully formed sentence ready for return.
Result Construction
After the recursive exploration finishes, the public method returns the populated result vector.
dp(s, "");
return result;
The empty string passed as the initial previous value ensures that the first word added will not be preceded by any extraneous characters. The final output consists of all possible sentences where the original string is completely broken into dictionary words, each sentence separated by a single space between words.
ELI5 - Simplified Explanation
Imagine you have a long string of letters that are all squished together, and your job is to find all the secret words hidden inside it. To solve this, you start with a big pile of known words. You look at the letters from the beginning and take a tiny piece at a time to see if that piece matches a word in your pile.
When you find a match, you stick that word aside, add a little space after it, and then jump to the rest of the letters to start looking for more words. You keep going like this until all the letters are used up. If you manage to use all the letters and finish with a clean sequence of words, that sequence gets saved as a successful solution.
Think of it like a treasure hunt where you keep branching off onto different paths. Every time you find a word, you explore the next part of the story. If you hit a point where you cannot find any more words but there are letters left over, you just stop and try a different path instead. Once all the paths have been explored, you have collected every possible way to write out those letters using the words you know.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | Python | C# | Java | Go | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| FelixFan1122 | C# | |||||||||
| fpdjsns | Python | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C#, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| FelixFan1122 | C# | |||||||||
| fpdjsns | Python | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ |
Videos
Similar Problems
- problem 139: Word Break
- problem 472: Concatenated Words
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality