KatInterview

Encode Keypad Multi-Tap Strokes

StringsAuto-graded · 21 test cases
EasyAuto-gradedStringsstringshash-tablesimulation

Last updated

Simulate telephone keypad multi-tap text encoding while inserting pause delimiters for consecutive letters on the same digit key.

On a standard phone keypad, numbers 2 through 9 correspond to letters as follows:

  • 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

In traditional multi-tap text entry, pressing a number key multiple times selects different letters on that key. For instance, pressing 2 once outputs 'A', twice outputs 'B', and three times outputs 'C'.

Write a function to convert an input string into its corresponding sequence of multi-tap keypad presses under the following conditions:

  1. Case-Insensitive: Uppercase and lowercase versions of a letter produce identical button presses (e.g., 'a' and 'A' both map to "2").
  2. Ignore Whitespace: Space characters (' ') in the input string should be completely skipped and produce no output.
  3. Same-Key Separators: If two consecutive output letters share the same digit key, insert a single space (' ') between their digit press sequences to represent the necessary pause between taps. Consecutive letters assigned to different digit keys require no space between them.

Constraints

  • $0 \le \text{len}(text) \le 10^5$
  • text consists solely of English letters ('a'–'z', 'A'–'Z') and space characters (' ').

Examples

Example 1

Input: encode_keypad('hello')

Output: '4433555 555666'

Example 2

Input: encode_keypad('A B')

Output: '2 22'

Example 3

Input: encode_keypad('')

Output: ''

Hints

Hint 1

Precompute a lookup mapping each uppercase letter to a tuple of (digit_key, press_string) to make encoding each character O(1).

Hint 2

Process the string character by character while keeping track of the digit key used by the most recently processed letter.

Hint 3

Ignore spaces entirely, but if a letter uses the same digit key as the previous letter, append a space delimiter before adding its press sequence.