#17

Letter Combinations of a Phone Number

Medium
Hash TableStringBacktrackingHash MapArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution (Backtracking)
Time
O(3^n * 4^m)
O(3^n * 4^m)
Space
O(n)
O(n)
💡

Intuition

Time O(3^n * 4^m)Space O(n)

The optimal approach uses backtracking to efficiently explore all combinations of letters. This method allows us to build combinations incrementally and backtrack when we reach the end of a combination, ensuring we only store valid combinations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a mapping of digits to their corresponding letters.
  2. 2Step 2: Define a backtracking function that builds combinations recursively.
  3. 3Step 3: Use a list to collect valid combinations and return it after exploring all possibilities.
solution.py28 lines
1# Full working Python code with comments
2
3def letter_combinations(digits):
4    if not digits:
5        return []
6
7    digit_to_letters = {
8        '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
9        '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
10    }
11
12    combinations = []
13
14    def backtrack(index, path):
15        if index == len(digits):
16            combinations.append(''.join(path))
17            return
18        letters = digit_to_letters[digits[index]]
19        for letter in letters:
20            path.append(letter)
21            backtrack(index + 1, path)
22            path.pop()
23
24    backtrack(0, [])
25    return combinations
26
27# Example usage
28print(letter_combinations('23'))

Complexity note: The time complexity is similar to the brute force approach, but with a more structured way of generating combinations, making it efficient in terms of memory usage and clarity.

  • 1Recognizing that each digit corresponds to a fixed set of letters allows us to use a mapping structure, which simplifies the problem significantly.
  • 2Understanding that backtracking can be used to explore all combinations incrementally helps in efficiently generating the required outputs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.