Letter Combinations of a Phone Number
Backtracking/Bruteforce builder
Last updated
Was this helpful?
Backtracking/Bruteforce builder
Last updated
Was this helpful?
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. Note that 1 does not map to any letters.
For example:
How can we map the letters to the numbers? With a dictionary?
Yes. We can map each letter to it's corresponding numbers and in out for-loop we refernce the number key in the dictionary so we can loop through the letters. We DO NOT loop through the numbers
We DO NOT loop through the numbers. We only loop through the letters of the numbers. To handle "looping" through the numbers, in our recursion method we just call on the next number in the input digit with digit[1: ]. This retrieves the next digit and the for-loop will iterate through it's characters.
We use a dictionary in order to map the letters to the numbers
It is important you realize, again, we DO NOT loop through the numbers. We only loop through the letters which we retrieve from the dictionary with the number as key.
Time: because at most there will be forks (because of the letters in 7 and 9 on the phone) and it will be done n times for each number given (see the Thought Process picture above)
Space: is the most calls the recursion stack will use