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 <= 4digits[i] is a digit in the range ['2', '9'].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:
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:
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_combinationsTo 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:
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| Case | How to Handle |
|---|---|
| Empty string input | Return an empty array immediately as no combinations can be formed from zero digits |
| Single digit input string | 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 | 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 | 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 | Python and other languages handle the maximum recursion depth of four easily without exceeding stack limits |
| Combinations return order requirements | The problem accepts results in any order so standard lexicographical backtracking output is naturally valid |
| Memory constraints with exponential output growth | The output list naturally grows up to four to the power of four which consumes negligible memory for valid constraints |