Given a string of digits from 2 to 9 and the classic phone keypad mapping, return all possible letter combinations the number could represent.
MediumOn a phone keypad, each digit from 2 to 9 maps to a few letters:
2: abc 3: def 4: ghi 5: jkl 6: mno 7: pqrs 8: tuv 9: wxyz
Given a string digits containing only digits from 2 to 9, return every letter string the digits could spell, taking one letter for each digit. Return the strings in any order. If digits is empty, return an empty list.
Example 1
Input: digits = "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Each of the three letters for 2 pairs with each of the three letters for 3.
Example 2
Input: digits = "" Output: []
Constraints
0 <= digits.length <= 4- Each character of
digitsis a digit from2to9.
Approach
Every answer picks one letter for the first digit, one for the second and so on. That's a nested loop with one level per digit, and recursion gives you a nested loop whose depth matches the input.
Keep the letters chosen so far. At position i, loop over the letters for digits[i]: add one, recurse to position i + 1, then remove it so the next letter can take its place. When i reaches the end of digits, the chosen letters form a complete combination, so add it to the result. An empty input has no combinations, so return an empty list up front instead of a list holding one empty string.
Steps
- If
digitsis empty, return an empty list. - Define
build(i). Ifiequals the length ofdigits, save the current letters as a string and return. - Otherwise, for each letter mapped to
digits[i], append it, callbuild(i + 1)and remove it. - Call
build(0)and return the result.
Complexity
- Time:
O(4^n * n), wherenis the length ofdigits. A digit maps to at most 4 letters, and each combination takesO(n)to copy into a string. - Space:
O(n)for the recursion and the letters being built, not counting the output.
Common mistakes
- Returning
[""]for an empty input. Zero digits means zero combinations here. - Forgetting that
7and9map to four letters, not three. - Building a new string at every level instead of appending and removing one character, which adds extra copying.
Interview experiences
1 sharedRelated questions
Count total possible combinations of N-digit numbers in a mobile keypad.Given two strings (Word 1 and Word 2) and a list of valid words from a dictionary, return the minimum number of operations required to convert Word 1 to Word 2.Given two strings, return true if you could change 2 letters in the s string and return the goal string. If this isn't possible, return false.Related courses


