Encode Keypad Multi-Tap Strokes
StringsAuto-graded · 21 test casesLast 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, C3:D, E, F4:G, H, I5:J, K, L6:M, N, O7:P, Q, R, S8:T, U, V9: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:
- Case-Insensitive: Uppercase and lowercase versions of a letter produce identical button presses (e.g.,
'a'and'A'both map to"2"). - Ignore Whitespace: Space characters (
' ') in the input string should be completely skipped and produce no output. - 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$
textconsists 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to map characters in a string to their multi-tap telephone keypad representation while handling a specific separator rule for consecutive letters that share a keypad digit.
-
Precomputation: We can define the character groups for digits
2through9. Pre-building a dictionary that maps each character (uppercase) to a pair(digit_key, press_sequence)allows $O(1)$ lookups.- For instance,
'L'belongs to"JKL"(digit5, 3rd position), so it maps to("5", "555").
- For instance,
-
Sequential Encoding: Iterate through the string:
- Skip spaces without modifying the state.
- For each valid letter, look up its assigned key digit and press sequence.
- If the key digit matches the key digit of the previously processed letter, insert a space
' 'into our output list to signify a pause. - Append the press sequence to the output list and update our tracking variable
last_digit.
-
String Assembly: Join all collected pieces into a single string at the end.
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the length of
text. We perform a single linear pass over the input. Precomputing the 26-character dictionary takes $\mathcal{O}(1)$ time. - Space Complexity: $\mathcal{O}(N)$ to store the constructed result list and final returned string. Auxiliary storage for tracking state and the alphabet mapping is $\mathcal{O}(1)$.
def encode_keypad(text: str) -> str:
groups = ["ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]
# Precompute character mappings
key_map = {}
for offset, cluster in enumerate(groups):
digit = str(offset + 2)
for idx, char in enumerate(cluster):
key_map[char] = (digit, digit * (idx + 1))
out = []
last_digit = None
for ch in text:
if ch == ' ':
continue
digit, presses = key_map[ch.upper()]
if digit == last_digit:
out.append(' ')
out.append(presses)
last_digit = digit
return "".join(out)