Match Words to a Keypad Number Sequence
StringsAuto-graded · 23 test casesLast updated
Given a word list and a string of keypad digits, return the sorted words whose letters map to exactly that digit sequence, testing string encoding and filtering.
An old mobile phone keypad assigns letters to the digit keys 2 through 9 as follows:
| Key | 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 |
Pressing the key that holds each letter of a word, in order, yields a digit string. For instance, the word cat yields 228.
You are given a list of dictionary words and a string of digits. Find every dictionary word whose key presses produce exactly that digit string.
Task
Implement a function that takes words (the dictionary) and digits (the digit string) and returns the list of matching words.
Matching rule
A word matches if both of these hold:
- Its length equals the length of
digits. - For every position
i, the word'si-th letter appears on the key given by thei-th character ofdigits.
A word that is longer or shorter than digits never matches, even if one is a prefix of the other's encoding.
Output
- Return the matching words in ascending lexicographic order.
- If no word matches, return an empty list.
Constraints
1 <= len(words) <= 10^4, and all words are distinct.- Each word consists of 1 to 20 lowercase English letters.
1 <= len(digits) <= 20, anddigitscontains only the characters2through9.
Examples
Example 1
Input: words_for_number(['dog', 'fog', 'cat', 'act', 'bat', 'fod'], '364')
Output: ['dog', 'fog']
Example 2
Input: words_for_number(['home', 'good', 'gone', 'hood'], '4663')
Output: ['gone', 'good', 'home', 'hood']
Example 3
Input: words_for_number(['hello', 'hi'], '4355')
Output: []
Hints
Hint 1
Generating every letter combination from the digits can explode to roughly 4^20 strings. Think about going in the opposite direction.
Hint 2
Each letter belongs to exactly one key, so every word has a single well-defined digit encoding. Build a letter-to-digit lookup table.
Hint 3
Skip words whose length differs from the digit string, compare the encoded word with the digit string, and sort the survivors before returning.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Do not expand the digit string into letter combinations: a 20-digit input could produce up to 4^20 (about 10^12) candidates. Instead, run the mapping forward. Every letter lies on exactly one key, so each word has exactly one digit encoding. The problem then reduces to filtering the dictionary.
- Build a table mapping each of the 26 letters to its key digit.
- For each word, discard it if its length differs from
len(number). Otherwise encode it letter by letter and compare withnumber. - Sort the kept words and return them.
Why it is correct
A word matches exactly when its length equals len(number) and, at every position i, its i-th letter is on key number[i]. Because each letter has exactly one key, "letter is on key d" is the same as "keys[letter] == d". So the encoded word equals number precisely when the word satisfies the matching rule. The filter therefore keeps all matching words and nothing else. Words are distinct, so no deduplication is needed, and sorting yields the required order.
The explicit length check matters: without it, a longer word whose encoding merely starts with number could be wrongly accepted if one compared with a prefix-based or zip-based approach.
Complexity
Let n = len(words), L = len(number) (at most 20), and k the number of matches.
- Time: O(n + m · L + k · L · log k), where
mis the number of words with lengthL(the only ones that are encoded). With the given limits this is at most a few hundred thousand character operations. - Space: O(k · L) for the result, plus a constant-size lookup table.
Reference solution
def words_for_number(words: list[str], number: str) -> list[str]:
# Map each letter to the digit of the key that carries it.
keys = {}
for d, letters in (('2', 'abc'), ('3', 'def'), ('4', 'ghi'), ('5', 'jkl'),
('6', 'mno'), ('7', 'pqrs'), ('8', 'tuv'), ('9', 'wxyz')):
for ch in letters:
keys[ch] = d
# Keep words with matching length whose encoding equals the number.
out = [
w for w in words
if len(w) == len(number) and ''.join(keys[c] for c in w) == number
]
out.sort()
return out