Generate Every Letter String a Phone Keypad Digit Sequence Can Spell
HeadwaySoftware Engineer · Technical ScreenLast updated
Given a string of digits from 2 to 9, return every letter string those digits can spell on a standard phone keypad, in lexicographic order. It tests systematic enumeration of combinations, keys that carry four letters, and producing a deterministic output order.
On a standard telephone keypad, each of the digits 2 through 9 carries a set of letters:
| Digit | Letters |
|---|---|
| 2 | a b c |
| 3 | d e f |
| 4 | g h i |
| 5 | j k l |
| 6 | m n o |
| 7 | p q r s |
| 8 | t u v |
| 9 | w x y z |
Given a string of digits, return every letter string that the digits can spell, choosing one letter from the key of each digit.
The interview asked a variation of this keypad task; the variation itself was not described, so this console poses the base task.
Function Signature
def keypad_letter_strings(digits: str) -> list[str]:
Rules
- Every output string has the same length as
digits, and itsi-th letter is one of the letters on the key ofdigits[i]. - Return every such string exactly once.
- Return the strings in ascending lexicographic order.
Constraints
1 <= len(digits) <= 8- Every character of
digitsis one of2,3,4,5,6,7,8,9 - The output therefore has at most
4^8 = 65,536strings, each of length at most 8
Examples
Example 1
Input: digits = "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Key 2 offers a, b, c and key 3 offers d, e, f, giving 3 × 3 = 9 strings.
Example 2
Input: digits = "7"
Output: ["p", "q", "r", "s"]
Example 3
Input: digits = "92"
Output: ["wa", "wb", "wc", "xa", "xb", "xc", "ya", "yb", "yc", "za", "zb", "zc"]
Key 9 has four letters, so there are 4 × 3 = 12 strings, listed in lexicographic order.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.