KatInterview

Match Words to a Keypad Number Sequence

StringsAuto-graded · 23 test cases
EasyAuto-gradedStringsstringshashingsorting

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

KeyLetters
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

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's i-th letter appears on the key given by the i-th character of digits.

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, and digits contains only the characters 2 through 9.

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.