Problem 140

Abstract / Summary

Given a string and a list of words return all possible sentences made by adding spaces to the string such that each word is in the list

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
42 lines | 890 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.33 | σ = 1.47

Complexity Analysis

Time: exponential
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
44 links | 31 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Word Break 2 | Leetcode #140'
Techdose 19 mins
Word Break 2 | Leetcode #140
YouTube video 'Word Break II - Leetcode 140 - Python'
NeetCodeIO 21 mins
Word Break II - Leetcode 140 - Python
YouTube video 'Word Break II | 2 Recursion Approaches | Backtracking | Memoization | Tree Diagram | Leetcode 140'
codestorywithMIK 39 mins
Word Break II | 2 Recursion Approaches | Backtracking | Memoization | Tree Diagram | Leetcode 140
YouTube video 'word break II leetcode | word break 2 leetcode | leetcode 140 | dfs + memoization | hard'
Naresh Gupta 12 mins
word break II leetcode | word break 2 leetcode | leetcode 140 | dfs + memoization | hard
YouTube video 'WORD BREAK II | LEETCODE # 140 | PYTHON DFS SOLUTION'
Cracking FAANG 22 mins
WORD BREAK II | LEETCODE # 140 | PYTHON DFS SOLUTION
YouTube video '140. Word Break II | Word Break 2 | Dynamic Programming | Backtracking'
Aryan Mittal 32 mins
140. Word Break II | Word Break 2 | Dynamic Programming | Backtracking
YouTube video '[Java] Leetcode 140. Word Break II [DP Subsequence #8]'
Eric Programming 18 mins
[Java] Leetcode 140. Word Break II [DP Subsequence #8]
YouTube video 'Word Break II | Day 30 | DP Memoization [ July LeetCoding Challenge ] [ Leetcode #140 ] [ 2020 ]'
Algorithms Made Easy 6 mins
Word Break II | Day 30 | DP Memoization [ July LeetCoding Challenge ] [ Leetcode #140 ] [ 2020 ]
YouTube video '[English] LeetCode 140. Word Break II'
happygirlzt 11 mins
[English] LeetCode 140. Word Break II
YouTube video 'Word Break II | Leetcode 140 (Java Solution)'
The Tech Granth 18 mins
Word Break II | Leetcode 140 (Java Solution)
YouTube video 'Word Break II  (LeetCode 140)  (Hard) (Recursion+ Backtracking)'
CodeWithARB 33 mins
Word Break II (LeetCode 140) (Hard) (Recursion+ Backtracking)
YouTube video 'Daily Leetcode #121: Jul 30, 2020 - 140. Word Break II'
Programming Live with Larry 15 mins
Daily Leetcode #121: Jul 30, 2020 - 140. Word Break II
YouTube video '140. Word Break II (Updated video in description) (Leetcode Hard)'
Programming Live with Larry 35 mins
140. Word Break II (Updated video in description) (Leetcode Hard)
YouTube video 'LeetCode 140. Word Break II'
Happy Coding 26 mins
LeetCode 140. Word Break II
YouTube video 'Daily Leetcode #1516: May 25, 2024 - 140. Word Break II'
Programming Live with Larry 11 mins
Daily Leetcode #1516: May 25, 2024 - 140. Word Break II
YouTube video 'Facebook Coding Interview Question | Leetcode 140 | Word Break II'
WorkWithGoogler 22 mins
Facebook Coding Interview Question | Leetcode 140 | Word Break II
YouTube video 'LeetCode 140 - Word Break II - Java'
Alpha-Code 22 mins
LeetCode 140 - Word Break II - Java
YouTube video '137. Leetcode 140. Word Break II : JAVA'
Web Fusion with Bharadwaj 23 mins
137. Leetcode 140. Word Break II : JAVA
YouTube video 'Word Break II | LeetCode 140  | Java Solution | Backtracking | Strings | Developer Coder'
Developer Coder 21 mins
Word Break II | LeetCode 140 | Java Solution | Backtracking | Strings | Developer Coder
YouTube video 'Day 306: LeetCode Problem 140. Word Break II - Swift'
iOSxBank 15 mins
Day 306: LeetCode Problem 140. Word Break II - Swift
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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