Menu
CoddyTech

Letter Combinations of a Phone Number

MediumBacktrackingpython iconjava iconcpp iconc iconjs icon+10

On a phone keypad, each digit from 2 to 9 carries a few letters: 2 is abc, 3 is def, 4 is ghi, 5 is jkl, 6 is mno, 7 is pqrs, 8 is tuv and 9 is wxyz.

You get a string digits. Pick one letter for each digit, keeping the digits in their order, and you get one string the keys can type. Return every such string, sorted in lexicographic (dictionary) order. For "23" that is nine strings, from "ad" to "cf".

Function

letterCombinations(digits: string) → string-array
digitsstring
the digits pressed, each from 2 to 9
Returnsstring-array
every string the keys can type, in lexicographic order

Constraints

  • 1 ≤ digits.length ≤ 4
  • Every character of digits is a digit from 2 to 9.
  • The answer holds at most 44 = 256 strings.

Examples

Input
digits = "23"
Output
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Explanation
2 offers a, b, c and 3 offers d, e, f. Each first letter pairs with each second letter, so there are 3 × 3 = 9 strings, and listing them with the first letter changing slowest keeps them sorted.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Suppose you only want the combinations that are real words from a dictionary. How would you avoid building all 4^n strings first?

Reset code
def letterCombinations(digits):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

digits = "23"

Expected

["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]