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: abc
  • 3: def
  • 4: ghi
  • 5: jkl
  • 6: mno
  • 7: pqrs
  • 8: tuv
  • 9: 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 in text.
  • 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^5
  • text contains only ASCII letters ('a'–'z', 'A'–'Z') and spaces (' ').

Step-by-step walkthrough

  1. Understand the keypad rules

    On a classic 12-key phone keypad, each letter sits on one digit button from 2 through 9:

      [ 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 convert text (up to 10^5 letters and spaces) into button presses under three rules:

    1. Case-insensitive: 'A' and 'a' both produce "2".
    2. Ignore input spaces: spaces in text produce nothing in the output.
    3. 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').
  2. 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 + 2 assumes every button holds 3 letters. Because button 7 holds four letters (pqrs), that formula assigns 's' to button 8 ("8") instead of four presses of button 7 ("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: text can have 100,000 characters, producing up to 500,000 output characters. Because Python strings cannot be mutated in place, repeated concatenation can copy the growing string over and over. Appending small pieces to a Python list and calling "".join(pieces) once at the end is guaranteed linear time.
  3. Precompute the 26-letter lookup table

    For each letter, we need two pieces of information during our scan:

    1. Which button (key_digit) it belongs to, so we can check whether it matches the previous letter's button.
    2. Its tap string (press_sequence), such as "222" for 'c'.

    If a letter sits at 0-based index inside its button's string, it takes index + 1 presses of key_digit. Precomputing all 26 entries once outside encode_keypad makes every lookup O(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()
    
  4. Scan left to right while remembering the previous key

    Now walk through text character by character while keeping a single state variable previous_key (initialized to None):

    • When ch == " ": skip it immediately with continue, and leave previous_key unchanged. 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 ch is a letter: convert it to lowercase, look up (key_digit, press_sequence), append " " if key_digit == previous_key, append press_sequence, and update previous_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_key starts as None, 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)
    
  5. 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([]) -> ""
    
  6. 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). Building LETTER_TABLE visits 26 letters once (O(1)). During encode_keypad, each of the n characters does at most one .lower() call, one O(1) dictionary lookup, and at most two O(1) list appends; since each letter produces at most 4 digits plus 1 space, "".join(pieces) copies at most 5n characters in a single O(n) pass.
  • Space: O(n). The output string and the pieces list hold at most 2n fragments totaling at most 5n characters, while LETTER_TABLE uses O(1) fixed space for its 26 alphabet entries.

Edge cases

  • Empty string "" or all spaces " ": Every character is skipped (or the loop never runs), pieces stays empty, and "".join([]) returns "" with no stray spaces.
  • Four-press letters ('s' and 'z'): 's' is index 3 on key '7' ("7777") and 'z' is index 3 on 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 = None on an input space: Doing so makes "i G" output "4444" instead of "444 4".
  • Copying input spaces into the output: Spaces in text are ignored, not preserved; ' ' in the output means "pause between two same-key letters," not a word boundary.
  • Comparing lowercase_ch == previous_letter instead of key_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 // 3 and index % 3 instead of a keypad table: Fails on 's' through 'z' because button 7 has four letters.
  • Forgetting .lower() before looking up in LETTER_TABLE: Raises a KeyError on 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). Scan encoded with two pointers: skip ' ' characters, measure the length run_len of each streak of identical digit d, and append KEYPAD_GROUPS[d][run_len - 1] (validating d in KEYPAD_GROUPS and 1 <= run_len <= len(KEYPAD_GROUPS[d]) if malformed input is possible). Note that decoding recovers lowercase letters without original word spaces, since encode_keypad intentionally 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-entry LETTER_TABLE, you can write it as a Python generator (a function using yield that produces one chunk at a time lazily without buffering the whole result in RAM): read one character from the input iterator, yield " " when key_digit == previous_key, yield press_sequence, and update previous_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

Similar questions

More Epic Systems interview questions

All 3 Epic Systems questions →