KatInterview

Keypad Digit Prefix Word Lookup

StringsAuto-graded · 19 test cases
EasyAuto-gradedStringsbinary-searchprefixsorting

Last 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:

DigitLetters
2a b c
3d e f
4g h i
5j k l
6m n o
7p q r s
8t u v
9w 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 0 or 1 matches 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^5
  • 1 <= len(words[i]) <= 20; each word has only lowercase English letters, and all words are distinct
  • 1 <= len(queries) <= 10^4
  • 1 <= 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.