This is a common interview question and I know there are already loads of questions about it, but none that really help me, so here goes. The question is as follows:
Given a digit string, return all possible letter combinations that the number could represent if entered on a standard phone number pad.
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
I've written a basic, iterative (non-recursive) solution in python which seems to work:
letters = {
'1': '',
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
'0': ''
}
def combinations(number_string):
output = []
for index, number in enumerate(number_string):
temp_list = []
for letter in letters[number]:
if not letters:
continue
if index == 0:
output.append(letter)
else:
for combo in output:
temp_list.append(combo + letter)
if temp_list:
output = temp_list
return output
print(combinations('234'))
But what is the time complexity and why?
I understand that I am iterating through each element in the input string, which gives us at least O(n) right away.
Then for each of those elements, I am iterating through up to 4 possible letter combinations, so I understand that gets us to O(4n).
But for each of the letter combinations, I am then iterating over all the combinations already obtained (to modify each for the latest letter). This is where I get lost.