Problem
Given a string of digits from 2 to 9, return every letter combination the digits could represent on a phone keypad, where 2 maps to abc, 3 to def, and so on.
Approach
Map each digit to its letters, then build combinations with backtracking: pick one letter for the current digit, move to the next digit, and record the string once every digit has a letter.
An iterative version works too. Start with a list holding an empty string and, for each digit, extend every existing string with each of that digit's letters.
The solution files below implement this approach.
Complexity
- Time: O(4^n · n): up to four letters per digit, and each finished string takes O(n) to build.
- Space: O(n) for the recursion, excluding the output.
Edge cases
- An empty input returns an empty list, not a list with one empty string.
- Digits 7 and 9 map to four letters, so they grow the output fastest.