LeetSolved

Find solutions to all LeetCode problems here.

17.

Letter Combinations of a Phone Number

Medium

Problem Description

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

Examples

Input: 23
Output: ad,ae,af,bd,be,bf,cd,ce,cf

Input:
Output:

Input: 2
Output: a,b,c

Constraints

Approach to Solve

Use backtracking to generate all possible combinations.

Code Implementation

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits: return []
        phone = {
            '2': ['a', 'b', 'c'],
            '3': ['d', 'e', 'f'],
            '4': ['g', 'h', 'i'],
            '5': ['j', 'k', 'l'],
            '6': ['m', 'n', 'o'],
            '7': ['p', 'q', 'r', 's'],
            '8': ['t', 'u', 'v'],
            '9': ['w', 'x', 'y', 'z']
        }
        def backtrack(index, path):
            if index == len(digits):
                combinations.append(''.join(path))
                return
            for letter in phone[digits[index]]:
                path.append(letter)
                backtrack(index + 1, path)
                path.pop()
        combinations = []
        backtrack(0, [])
        return combinations

Explanation

The Letter Combinations of a Phone Number problem is solved using a backtracking approach. Here's a detailed explanation of the solution:

  1. First, we create a mapping of digits to their corresponding letters on a phone keypad. This is typically stored in a dictionary or map.

  2. We use a recursive backtracking function that takes the following parameters:

    • index: the current position in the input string
    • path: the current combination being built
    • result: the list to store all valid combinations
  3. The base case for the recursion is when the index reaches the end of the input string. At this point, we've built a complete combination, so we add it to the result.

  4. In the recursive step:

    • We get the letters corresponding to the current digit.
    • For each letter, we: a) Add it to the current path b) Recursively call the function with the next index c) Remove the letter from the path (backtrack)
  5. This process ensures that we explore all possible combinations.

  6. Time Complexity: O(4^n), where n is the length of the input string.

    • In the worst case (digits 7 or 9), each digit corresponds to 4 letters.
    • We have n levels of recursion, and at each level, we make up to 4 recursive calls.
  7. Space Complexity: O(n)

    • The recursion stack can go n levels deep in the worst case.
    • The space needed to store the result is not counted in space complexity analysis.
  8. Edge Cases:

    • If the input string is empty, we return an empty list.
  9. Optimizations:

    • We can use a StringBuilder (in Java) or a mutable string (in Python) to build the combinations more efficiently.
    • In languages like C++, we can pass the result vector by reference to avoid copying.

This approach efficiently generates all possible letter combinations for the given input digits, handling the varying number of letters per digit and exploring all possibilities through backtracking.

Complexity

  • Time Complexity: O(4^n)
  • Space Complexity: O(n)
Code copied to clipboard!