Tutorialspoint
Problem
Solution
Submissions

Letter Combinations of a Phone Number

Certification: Intermediate Level Accuracy: 100% Submissions: 1 Points: 10

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. The mapping of digits to letters is the same as on telephone buttons (like old mobile phones). Note that 1 does not map to any letters.

Example 1
  • Input: digits = "23"
  • Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
  • Explanation:
    • Digit '2' maps to letters ['a', 'b', 'c'].
    • Digit '3' maps to letters ['d', 'e', 'f'].
    • We need to find all combinations by taking one letter from each digit.
    • First digit '2' can be 'a', 'b', or 'c'.
    • Second digit '3' can be 'd', 'e', or 'f'.
    • All combinations: ad, ae, af, bd, be, bf, cd, ce, cf.
Example 2
  • Input: digits = ""
  • Output: []
  • Explanation:
    • Input string is empty.
    • No digits to process.
    • Return empty array.
    • No combinations possible with empty input.
Constraints
  • 0 ≤ digits.length ≤ 4
  • digits[i] is a digit in the range ['2', '9']
  • Each digit maps to 3 or 4 letters (except 7 and 9 which map to 4 letters)
  • Time Complexity: O(3^n * 4^m) where n and m are the number of digits mapping to 3 and 4 letters
  • Space Complexity: O(3^n * 4^m) for the output array
MapBacktracking PwCAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Create a mapping of digits to their corresponding letters using an object or map
  • Use backtracking to generate all possible combinations
  • Start with an empty string and build combinations character by character
  • For each digit, try all possible letters and recursively build the rest
  • When the combination length equals the input length, add it to the result

Steps to solve by this approach:

 Step 1: Handle the base case where input is empty and return empty array immediately.
 Step 2: Create a mapping object that maps each digit (2-9) to its corresponding letters.
 Step 3: Initialize an empty result array to store all valid combinations.
 Step 4: Define a backtracking function that takes current index and current combination string.
 Step 5: Base case: if index equals digits length, add current combination to result and return.
 Step 6: Get letters for current digit and iterate through each letter.
 Step 7: For each letter, recursively call backtrack with next index and updated combination.

Submitted Code :