C++ 0017.cpp
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty())
return {};
map<int, set<string>> dp;
dp[0] = { "" };
for (int i = 0; i < digits.size(); i++)
{
string choice;
switch (digits[i])
{
case '2': choice = "abc"; break;
case '3': choice = "def"; break;
case '4': choice = "ghi"; break;
case '5': choice = "jkl"; break;
case '6': choice = "mno"; break;
case '7': choice = "pqrs"; break;
case '8': choice = "tuv"; break;
case '9': choice = "wxyz"; break;
}
for (auto& prefix : dp[i])
for (auto c : choice)
dp[i+1].insert(prefix + c);
}
auto& final = dp[digits.size()];
return { final.begin(), final.end() };
}
};
Difficulty
and has an acceptance rate of about 67% (4+ million submissions).
Typical patterns to solve this problem:
- Backtracking
- Hash Table
- String
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 implementation generates all possible letter combinations that a string of telephone digits could represent, following the classic mapping of digits to letters on a phone keypad. It treats the problem as a dynamic-programming construction where each position in the input contributes a set of prefixes that are extended with the letters associated with the current digit. The algorithm returns the complete set of combinations in lexical order as a vector of strings.
Key Steps
The function begins by handling the trivial case of an empty input.
if (digits.empty())
return {};
A map named dp is created to store, for each index i, the set of all prefixes that can be formed from the first i digits. The base case is an empty prefix at index 0.
map<int, set<string>> dp;
dp[0] = { "" };
The main loop iterates over each character of the input string. For each digit, a choice string is populated with the corresponding letters using a switch statement.
for (int i = 0; i < digits.size(); i++)
{
string choice;
switch (digits[i])
{
case '2': choice = "abc"; break;
case '3': choice = "def"; break;
case '4': choice = "ghi"; break;
case '5': choice = "jkl"; break;
case '6': choice = "mno"; break;
case '7': choice = "pqrs"; break;
case '8': choice = "tuv"; break;
case '9': choice = "wxyz"; break;
}
// ...
}
Within the same iteration, every existing prefix stored at dp[i] is extended by each character in choice. The new strings are inserted into the set for the next index, dp[i+1].
for (auto& prefix : dp[i])
for (auto c : choice)
dp[i+1].insert(prefix + c);
After processing all digits, the final set of complete combinations is accessed via a reference to avoid an extra copy. The set is then transformed into a vector, preserving the sorted order provided by std::set.
auto& final = dp[digits.size()];
return { final.begin(), final.end() };
Edge Cases
The early return for an empty digits string ensures that the function produces an empty vector rather than a vector containing an empty string, which aligns with typical expectations for “no input”.
The switch statement covers only the digits '2' through '9'. Because the problem domain restricts input to these characters, any other character would simply leave choice empty, resulting in no new prefixes being generated for that position. This behavior naturally yields an empty result set for invalid inputs without additional checks.
The use of std::set for each DP entry guarantees that duplicate prefixes cannot appear, even if the same digit were processed multiple times. This property also means that the final output contains unique combinations only.
Performance Optimizations
The algorithm avoids unnecessary allocations by reusing the same dp map throughout the computation. Each iteration inserts directly into dp[i+1], eliminating the need for temporary containers.
Storing prefixes in a std::set provides automatic ordering, so the final conversion to a vector does not require an explicit sort step. The ordered nature of the set also prevents duplicate entries, removing the overhead of a separate deduplication pass.
The reference auto& final = dp[digits.size()]; binds directly to the stored set, allowing the constructor of the result vector to iterate over the set without copying it first. This reduces the number of string copies performed during the final stage.
By returning early for an empty input, the function bypasses the entire DP construction, saving both time and memory when no work is required.
ELI5 - Simplified Explanation
Imagine you have a telephone with letters on the buttons, just like the ones on some old phones. When you press a button, you can pick any of the letters on it. This code is like a helper that looks at a row of buttons you pressed and figures out every single word you could possibly make by picking one letter for each button.
First, the code checks to see if you pressed any buttons at all. If the phone is empty, there are no words to make. If you did press some buttons, the code starts with a blank piece of paper and gets ready to build the letters one by one.
It goes through each button one at a time. For the first button, it looks at the letters on that button and writes them down. Then, it looks at the next button and sticks those new letters onto the ends of the ones already on the paper. It keeps doing this, making longer and longer chains of letters for every button you pressed. By the time it reaches the last button, it has a giant collection of all the possible combinations you could have made. Finally, it gathers all those finished words together so you can see them.
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 | C++ | Python | Java | C# | Rust | JS | C | Go | PHP | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||||
| Progiez | C++ | Python | Java | |||||||||||
| github | aylei | Rust | ||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++ | |||||||||||||
| bujosa | Python | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lennylxx | C++ | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| MacJim | C++ | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| trung-hn | Python | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| zfang399 | C++ | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| black-shadows | C++, C++ | |||||||||||||
| bujosa | Python | |||||||||||||
| chandansgowda | Python | |||||||||||||
| charles-wangkai | Java | |||||||||||||
| chenyanzhe | C++ | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| FelixFan1122 | C# | |||||||||||||
| fengvyi | C++ | |||||||||||||
| fpdjsns | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| haoel | C++ | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| keineahnung2345 | C++ | |||||||||||||
| lennylxx | C++ | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| luangong | C++ | |||||||||||||
| MacJim | C++ | |||||||||||||
| qiyuangong | Java | |||||||||||||
| ruoru | Rust | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| trung-hn | Python | |||||||||||||
| varunu28 | Java | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| XiaotaoGuo | C++ | |||||||||||||
| yuanliu666 | Kotlin | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 39: Combination Sum
- problem 3014: Minimum Number of Pushes to Type Word I
- problem 3016: Minimum Number of Pushes to Type Word II
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
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