Problem 17

Abstract / Summary

Given a phone number string, list all possible letter combinations that the number could represent using the traditional phone keypad mapping.

Note

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

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() };
    }
};

33 lines | 998 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 67% (4+ million submissions).

Typical patterns to solve this problem:
  • Backtracking
  • Hash Table
  • String
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 6 | μ = 5.93 | σ = 1.44

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 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++
63 links | 44 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Letter Combinations of a Phone Number - Backtracking - Leetcode 17'
NeetCode 12 mins
Letter Combinations of a Phone Number - Backtracking - Leetcode 17
YouTube video 'LeetCode Tutorial 17. Letter Combinations of a Phone Number'
GoodTecher 25 mins
LeetCode Tutorial 17. Letter Combinations of a Phone Number
YouTube video 'Letter Combinations of a Phone Number - Leetcode 17 - Recursive Backtracking (Python)'
Greg Hogg 11 mins
Letter Combinations of a Phone Number - Leetcode 17 - Recursive Backtracking (Python)
YouTube video 'DSA Phir se with Sumeet | Leetcode 17 | Letter Combinations of a Phone Number'
Pepcoding 25 mins
DSA Phir se with Sumeet | Leetcode 17 | Letter Combinations of a Phone Number
YouTube video 'Letter Combinations of a Phone Number - LeetCode 17  - Backtracking'
One Code Man 6 mins
Letter Combinations of a Phone Number - LeetCode 17 - Backtracking
YouTube video 'Meta Coding Interview Question - LeetCode 17 - Letter Combinations of a Phone Number'
AlgoJS 5 mins
Meta Coding Interview Question - LeetCode 17 - Letter Combinations of a Phone Number
YouTube video 'Letter Combinations of a Phone Number (Iterative and Recursive!) LeetCode 17  #leetcode #leetcode75'
Deepti Talesra 19 mins
Letter Combinations of a Phone Number (Iterative and Recursive!) LeetCode 17 #leetcode #leetcode75
YouTube video 'Letter Combinations of a Phone Number - Iteration Method - LeetCode 17'
One Code Man 4 mins
Letter Combinations of a Phone Number - Iteration Method - LeetCode 17
YouTube video 'LeetCode 17. Letter Combinations of a Phone Number Explanation and Solution'
happygirlzt 7 mins
LeetCode 17. Letter Combinations of a Phone Number Explanation and Solution
YouTube video 'Letter Combinations of a Phone Number Python Solution - LeetCode #17'
Professor Oakes 6 mins
Letter Combinations of a Phone Number Python Solution - LeetCode #17
YouTube video 'Letter Combinations of a Phone Number - 17. LeetCode - Java'
Teddy Smith 10 mins
Letter Combinations of a Phone Number - 17. LeetCode - Java
YouTube video 'Letter Combinations of a Phone Number | Leetcode 17'
Coding Decoded 9 mins
Letter Combinations of a Phone Number | Leetcode 17
YouTube video 'Daily Leetcode #769: May 09, 2022 - 17. Letter Combinations of a Phone Number'
Programming Live with Larry 9 mins
Daily Leetcode #769: May 09, 2022 - 17. Letter Combinations of a Phone Number
YouTube video '17. Letter Combinations of a Phone Number | Daily Leetcode Challenge | August | C++ | Java'
Mayur Programming Club 36 mins
17. Letter Combinations of a Phone Number | Daily Leetcode Challenge | August | C++ | Java
YouTube video 'Leetcode 17 - Letter Combinations of a Phone Number (JAVA Solution Explained!)'
LC Bear 12 mins
Leetcode 17 - Letter Combinations of a Phone Number (JAVA Solution Explained!)
YouTube video 'Leetcode 17: Letter Combinations of a Phone Number'
Algorithms Casts 29 mins
Leetcode 17: Letter Combinations of a Phone Number
YouTube video 'Letter Combinations of a Phone Number | LeetCode 17 | Coders Camp'
Coders Camp 13 mins
Letter Combinations of a Phone Number | LeetCode 17 | Coders Camp
YouTube video 'LeetCode: 17. Letter Combinations of a Phone Number (Visualized)'
Code With Zi 13 mins
LeetCode: 17. Letter Combinations of a Phone Number (Visualized)
YouTube video 'Daily Leetcode #373: Apr 08, 2021 - 17. Letter Combinations of a Phone Number'
Programming Live with Larry 11 mins
Daily Leetcode #373: Apr 08, 2021 - 17. Letter Combinations of a Phone Number
YouTube video 'Leetcode 17 - Letter Combinations of a Phone Number | Recursion JS Solution'
Web Coder Abhishek 6 mins
Leetcode 17 - Letter Combinations of a Phone Number | Recursion JS Solution
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 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