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 digit to letters (just like on the telephone buttons) is given below:
Example:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
We’ll use a backtracking approach to solve this problem. Here’s a step-by-step strategy:
digits
input, append it to the result.def letterCombinations(digits):
if not digits:
return []
# Mapping from digit to corresponding letters
phone_map = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"
}
result = []
# Backtracking function
def backtrack(index, path):
# If the path length matches the digits length, we have a combination
if index == len(digits):
result.append("".join(path))
return
# Get letters that the current digit maps to
possible_letters = phone_map[digits[index]]
for letter in possible_letters:
path.append(letter) # Make a choice
backtrack(index + 1, path) # Explore with that choice
path.pop() # Undo the choice
# Initiate backtracking
backtrack(0, [])
return result
# Example usage
print(letterCombinations("23")) # Output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
The time complexity of this solution is O(4^n)
where n
is the length of the input digits
. This is because each digit can map to at most 4 letters and we are generating all possible combinations. For each combination, we perform a certain fixed operation, leading to this complexity.
Space Complexity: The space complexity is also O(4^n)
to store the result plus the space used by the recursion stack, which means in the worst case, it will take space proportional to the number of combinations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?