Convert a Sentence into its equivalent mobile numeric keypad sequence

Pattern: String building

medium

On an old phone keypad, each letter is typed by pressing one key a few times. Store the 26 key sequences in a table indexed by letter, write a 0 for each space, and join the pieces.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

On an old mobile keypad, key 2 has ABC, 3 has DEF, 4 has GHI, 5 has JKL, 6 has MNO, 7 has PQRS, 8 has TUV and 9 has WXYZ. A letter is typed by pressing its key once for the first letter on it, twice for the second, and so on. So C is 222 and S is 7777. A space is the 0 key. Given a sentence of capital letters and spaces, return the key presses as one string. For example, "HELLO WORLD" gives "4433555555666096667775553".

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name printSequence is this guide's own.

Think first

  • Does each letter's sequence depend on anything except the letter?
  • How can you get a letter's sequence in O(1)?
  • How do you build the answer efficiently?

Hints

    Brute force, and why it fails

    A long chain of if statements, one per letter, works but is easy to get wrong. A table is shorter and checked at a glance. Both are O(n).

    The key insight

    When an output depends only on one input character, the cleanest code is a lookup table.

    Dry run

    S0 
    O1 
    2 
    S3 

    s = SO S. The table says S is 7777 and O is 666. A space is 0.

    Step 1 of 4

    The plan

    KEYS = ["2", "22", "222", "3", "33", "333", …, "9", "99", "999", "9999"]   # A to Z
    out = empty builder
    for each c in s:
        if c == ' ': append "0"
        else: append KEYS[c - 'A']
    return out
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each character adds at most 4 digits. The output takes O(n).

    Edge cases

    • Letters on 4-press keys, S and Z: 7777 and 9999.
    • A single letter: its sequence.
    • Several spaces: one 0 each.
    I've built my logic, show the code

    Java

    class Solution {
        private static final String[] KEYS = {"2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555",
            "6", "66", "666", "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999"};   // A to Z
    
        public String printSequence(String s) {
            StringBuilder out = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == ' ') out.append('0');                     // a space is the 0 key
                else out.append(KEYS[c - 'A']);
            }
            return out.toString();
        }
    }

    C++

    class Solution {
    public:
        string printSequence(string s) {
            static const char* KEYS[26] = {"2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555",
                "6", "66", "666", "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999"};   // A to Z
            string out;
            for (char c : s) {
                if (c == ' ') out += '0';                          // a space is the 0 key
                else out += KEYS[c - 'A'];
            }
            return out;
        }
    };

    Python

    class Solution:
        KEYS = ["2", "22", "222", "3", "33", "333", "4", "44", "444", "5", "55", "555", "6", "66", "666",
                "7", "77", "777", "7777", "8", "88", "888", "9", "99", "999", "9999"]   # A to Z
    
        def printSequence(self, s: str) -> str:
            return "".join("0" if c == " " else self.KEYS[ord(c) - ord("A")] for c in s)   # a space is the 0 key

    Common mistakes

    • Giving keys 7 and 9 only three letters, which shifts every letter after S.
    • Forgetting the space.
    • Building the answer with string + in a Java loop.

    Similar problems