Taro Logo

Letter Combinations of a Phone Number

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+32
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
StringsRecursion

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.

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if the input string is empty?
  2. Are we guaranteed that the input string will only contain digits from 2 to 9, or could it contain invalid characters like '0', '1', or symbols?
  3. Is there a specific ordering required for the resulting combinations in the returned list, or does any order suffice?
  4. Can I assume the output is expected as a list of strings, or is there a specific data structure you prefer?
  5. What is the maximum length of the input string we should expect for this problem?

Brute Force Solution

Approach

Imagine you are trying to guess a combination lock where each digit on a phone keypad gives you a few possible letters to choose from. The brute force strategy involves testing every single possible string combination by making every possible choice at each step until you have tried them all.

Here's how the algorithm would work step-by-step:

  1. Look at the first digit of the phone number and see what letters match it on the keypad.
  2. For each of those letters, move on to the second digit of the phone number and see what letters match it.
  3. Combine the first letter you chose with every possible letter from the second digit.
  4. If there are more digits, continue this process by adding every possible matching letter for the next digit to your growing combinations.
  5. Keep branching out your choices until you have reached the end of the phone number sequence.
  6. Collect every single complete letter combination that you formed along the way.
  7. Return the full collection of all possible combinations you generated.

Code Implementation

class Solution:
    def letterCombinations(self, digits: str) -> list[str]:
        if not digits:
            return []

        keypad_mapping = {
            "2": "abc",
            "3": "def",
            "4": "ghi",
            "5": "jkl",
            "6": "mno",
            "7": "pqrs",
            "8": "tuv",
            "9": "wxyz"
        }

        # Initialize collection with an empty string to build initial combinations properly        accumulated_combinations = [""]

        for current_digit in digits:
            next_level_combinations = []

            # Branch out current paths by appending every possible letter for this new digit
            for existing_combination in accumulated_combinations:
                for possible_letter in keypad_mapping[current_digit]:
                    next_level_combinations.append(existing_combination + possible_letter)

            accumulated_combinations = next_level_combinations

        # Return the final collection once all digits in the sequence have been fully processed
        return accumulated_combinations

Big(O) Analysis

Time Complexity
O(4^n) – For each digit in the phone number input of size n, we branch out into multiple choices corresponding to the letters on the keypad, averaging about 3 to 4 options per digit. At each step of our recursive exploration, the number of active combinations multiplies by this branching factor, leading to a tree of choices. Across n digits, this results in roughly 4 to the power of n total operations to build and collect every complete combination. Simplifying this exponential growth gives us a final time complexity of O(4^n).
Space Complexity
O(N) – To determine the auxiliary space complexity where N represents the number of digits in the phone number, we must examine the recursion stack and the output storage. The recursive backtracking function builds combinations character by character, creating a call stack that grows to a maximum depth of N corresponding to the length of the input digits. Additionally, the final results list stores up to 4 to the power of N combinations, but since this output is required by the problem statement, the extra memory used strictly by our algorithm consists of the recursive call stack frames scaling linearly with N. Therefore, the auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

To find all possible letter combinations for a phone number, we can use a branching approach that builds words step by step. We visit each digit one by one, branching out into all the possible letters attached to that digit until we complete a full combination.

Here's how the algorithm would work step-by-step:

  1. Look at the first digit of the phone number and note all the letters it represents.
  2. Take the first letter and prepare to add the options from the next digit to it.
  3. Continue this process of adding one letter from each successive digit until you reach the end of the phone number, creating a complete combination.
  4. Once a full combination of letters is formed, save it to your collection of results.
  5. Step back to the previous digit to try the next available letter, repeating the branching process until every possible path is explored.
  6. Ensure that if the phone number is completely empty, you simply return nothing.
  7. By systematically exploring every branch without skipping or repeating, you successfully gather all possible letter combinations.

Code Implementation

class Solution:
    def letterCombinations(self, digits: str) -> list[str]:
        if not digits:
            return []

        phone_mapping = {
            "2": "abc", "3": "def", "4": "ghi", "5": "jkl",
            "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"
        }

        collected_results = []

        # We use backtracking to explore every possible letter combination branch.        def backtrack(index_pointer: int, current_path: list[str]) -> None:
            if index_pointer == len(digits):
                collected_results.append("".join(current_path))
                return

            target_digit = digits[index_pointer]
            # Iterating through available letters ensures we explore every branch.
            for letter_option in phone_mapping[target_digit]:
                current_path.append(letter_option)
                backtrack(index_pointer + 1, current_path)
                current_path.pop()

        backtrack(0, [])
        # Returning all collected combinations after exploring every branch.
        return collected_results

Big(O) Analysis

Time Complexity
O(4^n) – In this backtracking approach, the input size n represents the number of digits in the phone string. Each digit maps to a maximum of 4 letters, creating a branching decision tree with a depth equal to n. To build all possible letter combinations, the algorithm visits every leaf node in a tree that grows at a rate of 4 raised to the power of n. This exponential branching leads to approximately 4^n operations, which simplifies in Big O notation to O(4^n).
Space Complexity
O(4^N) – The auxiliary space is primarily driven by the recursion stack, which reaches a maximum depth of N where N is the length of the phone number string, and the storage required for the output results list. Since a digit can map to up to 4 letters, the number of complete combinations grows exponentially, resulting in up to 4^N strings stored in memory. Therefore, the total extra memory consumed by both the call stack and the final collection scales exponentially with the input size N.

Edge Cases

Empty string input
How to Handle:
Return an empty array immediately as no combinations can be formed from zero digits
Single digit input string
How to Handle:
The backtracking function iterates directly over the mapped letters for that single digit and returns them as individual strings
Maximum allowed input length of four digits
How to Handle:
The recursive backtracking approach scales efficiently within time complexity limits since the maximum branch factor is four
Digits with four corresponding letters like seven and nine
How to Handle:
The digit-to-letter mapping hash map correctly maps these digits to four characters to ensure all branches are explored
Deep recursion stack overflow for long inputs
How to Handle:
Python and other languages handle the maximum recursion depth of four easily without exceeding stack limits
Combinations return order requirements
How to Handle:
The problem accepts results in any order so standard lexicographical backtracking output is naturally valid
Memory constraints with exponential output growth
How to Handle:
The output list naturally grows up to four to the power of four which consumes negligible memory for valid constraints
0/75 completed