Multi-Tap Phone Keypad String Encoder
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Classic numeric phone pads group the 26 English letters onto digit keys 2 through 9:
2:abc3:def4:ghi5:jkl6:mno7:pqrs8:tuv9:wxyz
Under multi-tap text entry, typing the 1st, 2nd, 3rd, or 4th letter assigned to a button requires tapping that digit 1, 2, 3, or 4 times in succession (for instance, 'd' produces "3" and 's' produces "7777").
Implement the following function to convert text into its multi-tap digit string:
def encode_keypad(text: str) -> str:
Apply these three encoding rules:
- Case insensitivity: Treat uppercase and lowercase letters identically (
'G'and'g'both map to"4"). - Omit input spaces: Ignore every
' 'character present intext. - Pause on consecutive same-button letters: Whenever two adjacent encoded letters live on the same digit button, place a single
' 'space between their digit runs so their taps do not run together. No separator is placed between consecutive letters on different buttons.
Examples
Example 1
Input: text = "notes"
Output: "66 6668337777"
'n' ("66") and 'o' ("666") both use button 6, so a ' ' pause separates them ("66 666"). The remaining letters 't' ("8"), 'e' ("33"), and 's' ("7777") each switch buttons and concatenate directly without spaces.
Example 2
Input: text = "Hi Go"
Output: "44 444 4666"
'H' ("44") and 'i' ("444") share button 4 ("44 444"). Dropping the input space leaves 'i' directly followed by 'G' ("4"), which also uses button 4, requiring a second ' ' pause before "4", followed by 'o' ("666").
Example 3
Input: text = " "
Output: ""
Every character in text is a space, so all characters are skipped and the encoded result is empty.
Constraints
0 <= len(text) <= 10^5textcontains only ASCII letters ('a'–'z','A'–'Z') and spaces (' ').
Step-by-step walkthrough
Understand the keypad rules
On a classic 12-key phone keypad, each letter sits on one digit button from
2through9:[ 2: abc ] [ 3: def ] [ 4: ghi ] [ 5: jkl ] [ 6: mno ] [ 7: pqrs ] [ 8: tuv ] [ 9: wxyz ] ^^^^ ^^^^ (4 letters!) (4 letters!)Typing a letter in multi-tap mode means pressing its button once for the 1st letter, twice for the 2nd, three times for the 3rd, or four times for the 4th (
's' -> "7777",'z' -> "9999"). We converttext(up to10^5letters and spaces) into button presses under three rules:- Case-insensitive:
'A'and'a'both produce"2". - Ignore input spaces: spaces in
textproduce nothing in the output. - Pause between same-key letters: whenever two consecutive encoded letters use the same digit key, insert a single
' 'between them so"ab"becomes"2 22"rather than the ambiguous"222"('c').
- Case-insensitive:
Why arithmetic shortcuts and string concatenation fall short
Before coding, watch out for two common traps:
- Do not divide alphabet index by 3: a formula like
key = (ord(ch) - ord('a')) // 3 + 2assumes every button holds 3 letters. Because button7holds four letters (pqrs), that formula assigns's'to button8("8") instead of four presses of button7("7777"), and shifts every letter after's'as well. Building a tiny 26-entry lookup dictionary directly from the keypad layout avoids index math altogether. - Do not build the output with
out += ...in a loop:textcan have100,000characters, producing up to500,000output characters. Because Python strings cannot be mutated in place, repeated concatenation can copy the growing string over and over. Appending small pieces to a Pythonlistand calling"".join(pieces)once at the end is guaranteed linear time.
- Do not divide alphabet index by 3: a formula like
Precompute the 26-letter lookup table
For each letter, we need two pieces of information during our scan:
- Which button (
key_digit) it belongs to, so we can check whether it matches the previous letter's button. - Its tap string (
press_sequence), such as"222"for'c'.
If a letter sits at 0-based
indexinside its button's string, it takesindex + 1presses ofkey_digit. Precomputing all 26 entries once outsideencode_keypadmakes every lookupO(1).# KEYPAD_GROUPS: maps each telephone number key ('2'..'9') to its lowercase letters in tap order. # Note that keys '7' and '9' hold 4 letters, while all other keys hold 3. KEYPAD_GROUPS: Dict[str, str] = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz", } def build_lookup_table() -> Dict[str, Tuple[str, str]]: """Map each lowercase letter to (key_digit, press_sequence), e.g. 'c' -> ('2', '222').""" table: Dict[str, Tuple[str, str]] = {} for key_digit, letters in KEYPAD_GROUPS.items(): for index, letter in enumerate(letters): press_count = index + 1 press_sequence = key_digit * press_count table[letter] = (key_digit, press_sequence) return table # LETTER_TABLE: precomputed 26-entry lookup dictionary built once at import time. LETTER_TABLE: Dict[str, Tuple[str, str]] = build_lookup_table()- Which button (
Scan left to right while remembering the previous key
Now walk through
textcharacter by character while keeping a single state variableprevious_key(initialized toNone):- When
ch == " ": skip it immediately withcontinue, and leaveprevious_keyunchanged. Why? Because input spaces vanish completely! In"Hi Go", once the space is ignored,'i'and'G'sit right next to each other in the encoded output and both use button'4', so they still need a' 'pause ("44 444 4666"). - When
chis a letter: convert it to lowercase, look up(key_digit, press_sequence), append" "ifkey_digit == previous_key, appendpress_sequence, and updateprevious_key = key_digit.
Input: "Hi Go" ch = 'H' -> key '4', prev = None -> pieces = ["44"], prev becomes '4' ch = 'i' -> key '4', prev == '4' -> pieces = ["44", " ", "444"], prev becomes '4' ch = ' ' -> ignored! -> pieces = ["44", " ", "444"], prev STAYS '4' ch = 'G' -> key '4', prev == '4' -> pieces = ["44", " ", "444", " ", "4"], prev becomes '4' ch = 'o' -> key '6', prev == '4' -> pieces = [..., "666"], prev becomes '6' join -> "44 444 4666"Because
previous_keystarts asNone, the very first encoded letter never gets a leading space, and because spaces are only appended right before a real letter, the output never gets a trailing space either.def encode_keypad(text: str) -> str: # pieces: encoded digit sequences and ' ' pause separators, joined once at the end pieces: List[str] = [] # previous_key: keypad digit ('2'..'9') of the last encoded letter, or None at the start previous_key: Optional[str] = None for ch in text: if ch == " ": # Input spaces are ignored completely and must NOT reset previous_key, # because adjacent encoded letters like "i G" still land next to each other. continue lowercase_ch = ch.lower() key_digit, press_sequence = LETTER_TABLE[lowercase_ch] if key_digit == previous_key: # Consecutive letters on the same button need a ' ' pause so their taps stay distinct. pieces.append(" ") pieces.append(press_sequence) previous_key = key_digit return "".join(pieces)- When
Trace the examples step by step
Let's walk through Example 1 (
"notes") and Example 3 (" "):Example 1: text = "notes" Step ch key_digit previous_key pause? press_sequence output so far ---- --- --------- ------------ ------ -------------- ---------------- 1 'n' '6' None no "66" "66" 2 'o' '6' '6' YES "666" "66 666" 3 't' '8' '6' no "8" "66 6668" 4 'e' '3' '8' no "33" "66 666833" 5 's' '7' '3' no "7777" "66 6668337777" Example 3: text = " " All 3 characters are spaces -> skipped -> "".join([]) -> ""Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # KEYPAD_GROUPS: maps each telephone number key ('2'..'9') to its lowercase letters in tap order. # Note that keys '7' and '9' hold 4 letters, while all other keys hold 3. KEYPAD_GROUPS: Dict[str, str] = { "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz", } def build_lookup_table() -> Dict[str, Tuple[str, str]]: """Map each lowercase letter to (key_digit, press_sequence), e.g. 'c' -> ('2', '222').""" table: Dict[str, Tuple[str, str]] = {} for key_digit, letters in KEYPAD_GROUPS.items(): for index, letter in enumerate(letters): press_count = index + 1 press_sequence = key_digit * press_count table[letter] = (key_digit, press_sequence) return table # LETTER_TABLE: precomputed 26-entry lookup dictionary built once at import time. LETTER_TABLE: Dict[str, Tuple[str, str]] = build_lookup_table() def encode_keypad(text: str) -> str: # pieces: encoded digit sequences and ' ' pause separators, joined once at the end pieces: List[str] = [] # previous_key: keypad digit ('2'..'9') of the last encoded letter, or None at the start previous_key: Optional[str] = None for ch in text: if ch == " ": # Input spaces are ignored completely and must NOT reset previous_key, # because adjacent encoded letters like "i G" still land next to each other. continue lowercase_ch = ch.lower() key_digit, press_sequence = LETTER_TABLE[lowercase_ch] if key_digit == previous_key: # Consecutive letters on the same button need a ' ' pause so their taps stay distinct. pieces.append(" ") pieces.append(press_sequence) previous_key = key_digit return "".join(pieces)✅ Submit now — all tests should pass.
Intuition & how it works
Picture texting on an old flip phone in multi-tap mode — a typing method where each numbered button cycles through three or four letters depending on how many times you press it in quick succession. If you press 6 twice for 'n' and immediately press 6 three times for 'o', the phone cannot tell 2 + 3 presses apart from one continuous streak! On a real phone you wait half a second so the cursor locks in 'n' before you start tapping 'o'; in our string encoding, a single space ' ' plays the role of that brief pause ("66 666"), while switching to a different button ('t' on 8, then 'e' on 3) locks in the letter automatically with no pause needed ("833").
Why do quick shortcuts go wrong here? First, trying to compute a letter's button with modulo-3 arithmetic (index // 3 and index % 3) breaks starting at 's', because buttons 7 (pqrs) and 9 (wxyz) hold four letters instead of three. Second, resetting your state when you see a space in the input breaks "Hi Go": input spaces are stripped away completely, leaving 'i' and 'G' adjacent on button 4, so forgetting the pause merges "444" and "4" into "4444". Third, repeatedly appending to an immutable string (a string object that cannot be modified in place, so growing it may copy the entire string again and again) can slow down to O(n^2) on 100,000 characters, whereas precomputing a 26-entry hash table (a key-value dictionary with O(1) average lookup time) and joining a list of fragments once runs cleanly in O(n) time.
Let's trace "Hi Go" (Example 2) step by step to watch previous_key ignore the input space and catch both repeated uses of button 4:
ch Action previous_key pieces appended
---- ---------------------------------- ------------ ---------------
'H' lower -> 'h' -> ('4', "44") None -> '4' "44"
'i' lower -> 'i' -> ('4', "444"), ==4! '4' -> '4' " ", "444"
' ' input space -> skip! stays '4' (nothing)
'G' lower -> 'g' -> ('4', "4"), ==4! '4' -> '4' " ", "4"
'o' lower -> 'o' -> ('6', "666") '4' -> '6' "666"
Joined result: "44 444 4666"
Complexity
Let n be the length of text.
- Time:
O(n). BuildingLETTER_TABLEvisits26letters once (O(1)). Duringencode_keypad, each of thencharacters does at most one.lower()call, oneO(1)dictionary lookup, and at most twoO(1)list appends; since each letter produces at most4digits plus1space,"".join(pieces)copies at most5ncharacters in a singleO(n)pass. - Space:
O(n). The output string and thepieceslist hold at most2nfragments totaling at most5ncharacters, whileLETTER_TABLEusesO(1)fixed space for its26alphabet entries.
Edge cases
- Empty string
""or all spaces" ": Every character is skipped (or the loop never runs),piecesstays empty, and"".join([])returns""with no stray spaces. - Four-press letters (
's'and'z'):'s'is index3on key'7'("7777") and'z'is index3on key'9'("9999"). - Different letters on the same key:
"no"produces"66 666"because'n'and'o'share button'6'even though they are different letters. - Same-key letters separated by input spaces:
"Hi Go"and"l l"drop the input spaces and still emit the required pauses ("44 444 4666"and"555 555"). - Alternating keys:
"SOS"alternates buttons'7'and'6', producing"77776667777"with zero spaces. - Mixed uppercase and lowercase:
"NoTeS"normalizes every letter via.lower()and produces the exact same"66 6668337777"as"notes".
Common mistakes
- Resetting
previous_key = Noneon an input space: Doing so makes"i G"output"4444"instead of"444 4". - Copying input spaces into the output: Spaces in
textare ignored, not preserved;' 'in the output means "pause between two same-key letters," not a word boundary. - Comparing
lowercase_ch == previous_letterinstead ofkey_digit == previous_key: A pause is needed whenever two consecutive letters share the same button ("no"->"66 666"), not only when the exact same letter repeats. - Using
index // 3andindex % 3instead of a keypad table: Fails on's'through'z'because button7has four letters. - Forgetting
.lower()before looking up inLETTER_TABLE: Raises aKeyErroron uppercase letters like'H'or'G'.
Follow-up questions
- How would you write the inverse decoder that turns a valid multi-tap digit string (with space pauses) back into lowercase letters? In any valid output from
encode_keypad, every letter is a maximal contiguous run of identical digits (because same-key neighbors are separated by' 'and different-key neighbors use different digits). Scanencodedwith two pointers: skip' 'characters, measure the lengthrun_lenof each streak of identical digitd, and appendKEYPAD_GROUPS[d][run_len - 1](validatingd in KEYPAD_GROUPSand1 <= run_len <= len(KEYPAD_GROUPS[d])if malformed input is possible). Note that decoding recovers lowercase letters without original word spaces, sinceencode_keypadintentionally discards case and input spaces. - How could you process an arbitrarily long character stream while keeping auxiliary working memory at O(1)? Auxiliary memory means the extra working space your algorithm uses beyond the input and output streams themselves. Because the encoder only needs to remember
previous_key(one character) plus the fixed 26-entryLETTER_TABLE, you can write it as a Python generator (a function usingyieldthat produces one chunk at a time lazily without buffering the whole result in RAM): read one character from the input iterator,yield " "whenkey_digit == previous_key,yield press_sequence, and updateprevious_key. - What data structures would you introduce to upgrade this encoder/decoder from multi-tap presses to single-press T9 word prediction? In T9 predictive text (a keypad system where you press each letter's button just once and a dictionary guesses the intended word),
"notes"becomes"66837"with no pauses needed, while input spaces become real word separators again. Because different words can share the same digit code (for example,"home"and"good"both map to"4663"), you precompute a dictionary mapping each digit string to matching words sorted by word frequency. To suggest completions while the user is still mid-word, index the vocabulary in a trie (a prefix tree where each path of digits'2'..'9'represents a typed prefix) and cache the top-ranked word completions at every node.
Follow-up questions
- How would you write the inverse decoder that turns a valid multi-tap digit string (with space pauses) back into lowercase letters?
- How could you process an arbitrarily long character stream while keeping auxiliary working memory at O(1)?
- What data structures would you introduce to upgrade this encoder/decoder from multi-tap presses to single-press T9 word prediction?
Similar questions
- Exponential Patch Growth and Coin Counts
- Propositional Implication Deduction Engine
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance