Keypad Spellings

Easy · Backtracking · about 15 min

An old phone keypad has letters on its keys: 2 = abc, 3 = def, 4 = ghi, 5 = jkl, 6 = mno, 7 = pqrs, 8 = tuv, 9 = wxyz. Given a string of digits (only 2 to 9, length 0 to 6), return every word you can spell by choosing one letter from each digit's key, in the same order as the digits.

  • Return the words sorted alphabetically.
  • An empty string of digits spells nothing: return [].

keypad_words("29") → ["aw", "ax", "ay", "az", "bw", "bx", "by", "bz", "cw", "cx", "cy", "cz"]

Hints

  • Think of a helper that knows which digit it is on and the word built so far.
  • When the helper has used every digit, record the word. Otherwise try each letter on the current key and move to the next digit.
  • Handle the empty input before you start: it should give an empty list, not a list with one empty word.

Learn the pattern first: the Backtracking lesson.

More Backtracking problems