Keypad Digit Prefix Word Lookup
StringsAuto-graded · 19 test casesLast updated
Encode words as keypad digit strings and answer many digit-prefix queries quickly using sorted ranges or a trie, returning matches in alphabetical order.
Keypad Digit Prefix Word Lookup
An old mobile phone has a keypad where each of the digits 2 through 9 stands for a group of lowercase 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 |
The digits 0 and 1 do not stand for any letters.
The keypad code of a word is the string you get by replacing every letter with the digit of its group. For instance, "cat" has code "228", and "tree" has code "8733".
You are given a list of distinct lowercase words and a list of queries. Each query is a non-empty string of digit characters ('0' to '9') describing the keys pressed so far. For each query, find every word whose keypad code begins with the query (the query is a prefix of the code, and a code equal to the query also counts). Return these words sorted in ascending alphabetical (lexicographic) order. If nothing matches, return an empty list for that query.
Write a function that takes words and queries and returns a list of lists: the i-th inner list holds the matching words for queries[i], in alphabetical order.
Notes:
- Any query containing
0or1matches nothing, because no word has those digits in its code. - Different words may share the same code (for example
"cat","bat"and"act"all have code"228"); all of them are returned when they match. - The result must be ordered by the words themselves, not by their codes.
- The output keeps the order of
queries, with one inner list per query.
Constraints
1 <= len(words) <= 10^51 <= len(words[i]) <= 20; each word has only lowercase English letters, and all words are distinct1 <= len(queries) <= 10^41 <= len(queries[i]) <= 20; each query has only the characters'0'to'9'- The total number of words returned over all queries is at most
10^6
Preprocess the dictionary once so that a query does not need to scan every word.
Examples
Example 1
Input: keypad_prefix_words(['cat', 'bat', 'act', 'car', 'care', 'dog'], ['228', '22', '2273', '364', '9'])
Output: [['act', 'bat', 'cat'], ['act', 'bat', 'car', 'care', 'cat'], ['care'], ['dog'], []]
Hints
Hint 1
Convert each word to its digit string once, up front, using a letter-to-digit table.
Hint 2
If you sort the digit strings, all strings that start with a given prefix form one contiguous block. Binary search can find its ends; for the upper end, use the prefix followed by a character just above '9'.
Hint 3
The block is ordered by code, not by word, so sort the matched words alphabetically before returning them.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Convert every word to its keypad code once. Sort the (code, word) pairs by code. In a sorted list of strings, all strings that start with a given prefix sit next to each other in a single block, so each query only needs to locate the two ends of that block.
For a query q:
lo = bisect_left(codes, q)is the first code that is>= q.hi = bisect_left(codes, q + ":")is the first code that is>= q + ":". The character':'comes right after'9'in ASCII, and codes contain only digits2to9, so every code starting withqis smaller thanq + ":".- The pairs in
[lo, hi)are exactly the words whose code starts withq. - Sort those words alphabetically and append them to the result.
Why it is correct
A code e lies in the range [q, q + ":") exactly when q is a prefix of e:
- If
qis a prefix ofe, thene >= q(a string is never smaller than its own prefix). At positionlen(q),eeither ends or has a digit, which is below':', soe < q + ":". - If
qis not a prefix ofe, then eithereis a proper prefix ofq(soe < q), or at the first differing positionehas a smaller digit thanq(soe < q), or a larger one (soe > q + ":"). In every caseefalls outside the range.
Queries with 0 or 1 give an empty range automatically, since no code contains those digits. A query that equals a code exactly is included because bisect_left lands on the first equal element.
The slice is ordered by code and only alphabetical within a single code, which is why the final per-query sort by word is required (for example, "car", "care", "act", "bat", "cat" must become "act", "bat", "car", "care", "cat").
Complexity
Let N be the number of words, L <= 20 the maximum length, Q the number of queries, and k the number of matches for a query.
- Preprocessing: encoding is
O(N * L), sorting isO(N * L * log N). - Per query: two binary searches cost
O(L * log N), and sorting the matches costsO(k * L * log k). - Space:
O(N * L)for codes and pairs, plus the output.
A digit trie that stores pre-sorted word lists per node is an alternative that gives O(L + k) per query, at the cost of more memory.
Reference solution
from bisect import bisect_left
from typing import List
def keypad_prefix_words(words: List[str], queries: List[str]) -> List[List[str]]:
groups = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
}
letter_to_digit = {}
for digit, letters in groups.items():
for ch in letters:
letter_to_digit[ch] = digit
# Sort (code, word) pairs so equal-prefix codes are contiguous.
pairs = sorted(("".join(letter_to_digit[ch] for ch in w), w) for w in words)
codes = [code for code, _ in pairs]
results = []
for q in queries:
lo = bisect_left(codes, q)
# ':' directly follows '9' in ASCII, so [q, q + ':') covers
# exactly the codes that start with q.
hi = bisect_left(codes, q + ":")
matched = [w for _, w in pairs[lo:hi]]
results.append(sorted(matched))
return results