KatInterview

Keypad Digit Sequence Word Filter

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringsstringshash-mapfiltering

Last updated

Filter a word list down to the words whose letters, read through a phone keypad, spell out a given digit string, in original order.

Keypad Digit Sequence Word Filter

An old mobile phone keypad assigns letters to the digit keys 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

Typing a word means pressing, for each of its letters, the key that holds that letter. This produces a digit string for the word.

You are given a string digits and a list of words dictionary. Return every word from dictionary whose typed digit string is exactly digits.

Matching rules

  • A word matches only if its length equals len(digits) and, at every position, the key holding the word's letter is the digit at that same position in digits.
  • Return matching words in the same order they appear in dictionary. If a word appears several times in dictionary, keep every copy.
  • If digits is empty, return an empty list.
  • The keys 0 and 1 (and any character that is not one of 2-9) hold no letters, so if digits contains such a character, no word can match and the result is an empty list.
  • A word containing a character that is not on the keypad (for example an uppercase letter) never matches.
  • If dictionary is empty or nothing matches, return an empty list.

Constraints

  • 0 <= len(digits) <= 10
  • 0 <= len(dictionary) <= 100,000
  • Each word consists of lowercase English letters.

Examples

Example 1

Input: find_words_for_digits('23', ['ad', 'ae', 'af', 'bd', 'cat'])

Output: ['ad', 'ae', 'af', 'bd']

Example 2

Input: find_words_for_digits('4663', ['good', 'home', 'gone', 'food'])

Output: ['good', 'home', 'gone']

Hints

Hint 1

Rather than generating every letter combination from the digits (which can reach about a million strings), convert each dictionary word into digits and compare.

Hint 2

Build a letter-to-digit lookup once. Then a word can be rejected immediately if its length differs from the length of digits, and also at the first position where its letter's key differs from the digit.

Hint 3

Handle the special cases up front: an empty digit string, or one containing a character outside 2-9, can never match anything, so return an empty list straight away.