Letter Combinations of a Phone Number - Problem

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Digit Mapping:

  • 2: ABC
  • 3: DEF
  • 4: GHI
  • 5: JKL
  • 6: MNO
  • 7: PQRS
  • 8: TUV
  • 9: WXYZ

Input & Output

Example 1 — Two Digits
$ Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
💡 Note: Digit 2 maps to 'abc', digit 3 maps to 'def'. Each letter from 2 combined with each letter from 3 gives 3×3=9 combinations.
Example 2 — Empty Input
$ Input: digits = ""
Output: []
💡 Note: Empty input string returns empty array as no digits to process.
Example 3 — Single Digit
$ Input: digits = "2"
Output: ["a","b","c"]
💡 Note: Single digit 2 maps to letters 'a', 'b', 'c', so return each letter as separate combination.

Constraints

  • 0 ≤ digits.length ≤ 4
  • digits[i] is a digit in the range ['2', '9']

Visualization

Tap to expand
Letter Combinations of a Phone Number INPUT 2 abc 3 def 4 ghi 5 jkl 6 mno 7 pqrs Input String: "23" Digit Mapping: 2 --> abc 3 --> def ALGORITHM STEPS 1 Initialize Mapping Create digit-to-letters map 2 Backtracking Setup Start with empty combination 3 Recursive Explore Try each letter for digit 4 Collect Results Add complete combinations Backtracking Tree: "" a b c ad ae af ... ... FINAL RESULT All Combinations (9 total): "ad" "ae" "af" "bd" "be" "bf" "cd" "ce" "cf" Output Array: ["ad","ae","af","bd","be", "bf","cd","ce","cf"] Complexity Analysis: Time: O(4^n * n) Space: O(n) recursion depth Status: OK - All 9 found Key Insight: Backtracking explores all possible combinations by building strings character by character. For each digit, we try all its mapped letters, recursively process the next digit, then backtrack to try other letters. Total combinations = product of letters per digit (3 x 3 = 9 for "23"). This generates a tree of depth n. TutorialsPoint - Letter Combinations of a Phone Number | Backtracking Approach
Asked in
Meta 45 Amazon 38 Google 32 Microsoft 28
68.0K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen