Letter Combinations of a Phone Number
MediumNeetCode 150Top Interview 150 BacktrackingLinkedInDropboxEpic SystemsFlexportProblem
On an old phone keypad, each digit from 2 to 9 stands for some letters: 2 is abc, 3 is
def, 4 is ghi, 5 is jkl, 6 is mno, 7 is pqrs,
8 is tuv and 9 is wxyz.
Given a string digits, return every word you could type by choosing one letter for each digit,
in order. The words may be returned in any order. If digits is empty, return an empty list.
Constraints
- 0 ≤ digits.length ≤ 4
- Each character of digits is a digit from '2' to '9'
Examples: pick one to animate
Solutions
Time: A digit has at most 4 letters, so there are at most 4^n words. Building each word into the answer costs O(n).
Space: Besides the output, the path and the recursion are at most n deep, one level per digit.
Fill the word left to right, one letter per digit. At position pos, try each letter of that digit:
add it, recurse for the next position, then remove it. When the position reaches the end of
digits, the path is a full word, so save it.