Keypad typing

Last Updated : 10 Jul, 2026

Given a string s consisting of lowercase English letters. Each letter corresponds to a number on a standard keypad, as shown in the figure. Replace every character in s with its corresponding keypad number and return the resulting numeric string.

blobid0_1777529736

Examples:

Input: s = "geeksforgeeks"
Output: 4335736743357
Explanation: Each character in the string "geeksforgeeks" is converted to its corresponding digit based on the keypad, and the digits are concatenated in order. This results in the number 4335736743357, which is the required decimal representation.

Input: s = "geeksquiz"
Output: 433577849
Explanation: Each character in the string "geeksquiz" is converted to its corresponding digit based on the keypad, and the digits are concatenated in order. This results in the number 433577849, which is the required decimal representation.

Try It Yourself
redirect icon

[Naive Approach] Linear Search in Keypad Groups - O(n * 8) Time and O(1) Space

The idea is to store the characters corresponding to each keypad digit (2–9) in separate strings. For every character in the input string, linearly search these keypad groups to determine which digit it belongs to, append that digit to the answer, and continue until all characters are processed.

C++
#include <iostream>
#include <string>
using namespace std;

string printNumber(string &s)
{

    // Keypad groups corresponding to digits 2 to 9.
    string keypad[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    string ans;

    // Process every character.
    for (char ch : s)
    {

        // Find the corresponding keypad group.
        for (int i = 0; i < 8; i++)
        {
            if (keypad[i].find(ch) != string::npos)
            {
                ans += char('2' + i);
                break;
            }
        }
    }

    return ans;
}

int main()
{

    string s = "geeksquiz";

    cout << printNumber(s);

    return 0;
}
Java
class GFG {

    static String printNumber(String s)
    {

        // Keypad groups corresponding to digits 2 to 9.
        String[] keypad = { "abc", "def",  "ghi", "jkl",
                            "mno", "pqrs", "tuv", "wxyz" };

        StringBuilder ans = new StringBuilder();

        // Process every character.
        for (char ch : s.toCharArray()) {

            // Find the corresponding keypad group.
            for (int i = 0; i < 8; i++) {
                if (keypad[i].indexOf(ch) != -1) {
                    ans.append((char)('2' + i));
                    break;
                }
            }
        }

        return ans.toString();
    }

    public static void main(String[] args)
    {

        String s = "geeksquiz";

        System.out.println(printNumber(s));
    }
}
Python
""" Keypad groups corresponding to digits 2 to 9. """
keypad = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]


def printNumber(s):

    ans = ""

    # Process every character.
    for ch in s:

        # Find the corresponding keypad group.
        for i in range(8):
            if ch in keypad[i]:
                ans += chr(ord('2') + i)
                break

    return ans


if __name__ == "__main__":
    s = "geeksquiz"

    print(printNumber(s))
C#
using System;

class GFG {
    static string printNumber(string s)
    {
        // Keypad groups corresponding to digits 2 to 9.
        string[] keypad = { "abc", "def",  "ghi", "jkl",
                            "mno", "pqrs", "tuv", "wxyz" };

        string ans = "";

        // Process every character.
        foreach(char ch in s)
        {
            // Find the corresponding keypad group.
            for (int i = 0; i < 8; i++) {
                if (keypad[i].Contains(ch)) {
                    ans += (char)('2' + i);
                    break;
                }
            }
        }

        return ans;
    }

    static void Main()
    {
        string s = "geeksquiz";

        Console.WriteLine(printNumber(s));
    }
}
JavaScript
"use strict";
// Keypad groups corresponding to digits 2 to 9.
const keypad = [
    "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
];

function printNumber(s)
{

    let ans = "";

    // Process every character.
    for (const ch of s) {

        // Find the corresponding keypad group.
        for (let i = 0; i < 8; i++) {
            if (keypad[i].includes(ch)) {
                ans += String.fromCharCode("2".charCodeAt(0)
                                           + i);
                break;
            }
        }
    }

    return ans;
}

// Driver Code
let s = "geeksquiz";

console.log(printNumber(s));

Output
433577849

[Better Approach] Using Digit Mapping - O(n) Time and O(1) Space

The idea is to create a direct mapping from every lowercase English letter ('a' to 'z') to its corresponding keypad digit. Then, traverse the string once and replace each character by looking up its mapped digit in constant time. This avoids searching through keypad groups for every character.

Working of Approach:

  • Create a lookup string mp where the character at index i stores the keypad digit corresponding to the letter ('a' + i).
  • Traverse the input string one character at a time.
  • For each character ch, compute its index as ch - 'a' and use it to directly access the corresponding digit from mp.
  • Append the retrieved digit to the answer string.
  • After all characters are processed, return the resulting numeric string.
C++
#include <iostream>
#include <string>
using namespace std;

string printNumber(string &s)
{

    // Mapping of 'a' to 'z' to keypad digits.
    string mp = "22233344455566677778889999";

    string ans;

    // Replace every character with its keypad digit.
    for (char ch : s)
    {
        ans += mp[ch - 'a'];
    }

    return ans;
}

int main()
{

    string s = "geeksquiz";

    cout << printNumber(s);

    return 0;
}
Java
class GFG {

    static String printNumber(String s)
    {

        // Mapping of 'a' to 'z' to keypad digits.
        String mp = "22233344455566677778889999";

        StringBuilder ans = new StringBuilder();

        // Replace every character with its keypad digit.
        for (char ch : s.toCharArray()) {
            ans.append(mp.charAt(ch - 'a'));
        }

        return ans.toString();
    }

    public static void main(String[] args)
    {

        String s = "geeksquiz";

        System.out.println(printNumber(s));
    }
}
Python
def printNumber(s):

    # Mapping of 'a' to 'z' to keypad digits.
    mp = "22233344455566677778889999"

    ans = ""

    # Replace every character with its keypad digit.
    for ch in s:
        ans += mp[ord(ch) - ord('a')]

    return ans


if __name__ == "__main__":

    s = "geeksquiz"

    print(printNumber(s))
C#
using System;

class GFG {
    static string printNumber(string s)
    {
        // Mapping of 'a' to 'z' to keypad digits.
        string mp = "22233344455566677778889999";

        string ans = "";

        // Replace every character with its keypad digit.
        foreach(char ch in s) { ans += mp[ch - 'a']; }

        return ans;
    }

    static void Main()
    {
        string s = "geeksquiz";

        Console.WriteLine(printNumber(s));
    }
}
JavaScript
// Mapping of 'a' to 'z' to keypad digits.
const mp = "22233344455566677778889999";

function printNumber(s)
{

    let ans = "";

    // Replace every character with its keypad digit.
    for (let ch of s) {
        ans += mp[ch.charCodeAt(0) - "a".charCodeAt(0)];
    }

    return ans;
}

// Driver Code
const s = "geeksquiz";

console.log(printNumber(s));

Output
433577849

[Expected Approach] Using Direct Character Classification - O(n) Time and O(1) Space

The idea is to traverse the string once and directly determine the corresponding keypad digit for each character using a chain of if-else conditions. Since every lowercase letter belongs to exactly one keypad group, each character is mapped to its digit in constant time and appended to the result string.

Let us understand with an example:
Input: s = "geeksquiz"

  • Initialize an empty string temp to store the keypad digits.
  • Traverse the input string "geeksquiz" one character at a time.
  • For each character, determine its corresponding keypad digit using the if-else conditions and append that digit to temp.
  • The characters are mapped as: g-> 4, e-> 3, e-> 3, k-> 5, s-> 7, q-> 7, u-> 8, i-> 4, z-> 9.
  • After processing all characters, temp becomes "433577849", which is returned as the final answer.
C++
#include <iostream>
#include <string>
using namespace std;

string printNumber(string &s)
{
    // Stores the resultant numeric string.
    string temp = "";

    // Traverse each character of the string.
    for (int i = 0; i < (int)s.length(); i++)
    {
        // Map characters to their corresponding keypad digit.
        if (s[i] == 'a' || s[i] == 'b' || s[i] == 'c')
            temp.push_back('2');
        else if (s[i] == 'd' || s[i] == 'e' || s[i] == 'f')
            temp.push_back('3');
        else if (s[i] == 'g' || s[i] == 'h' || s[i] == 'i')
            temp.push_back('4');
        else if (s[i] == 'j' || s[i] == 'k' || s[i] == 'l')
            temp.push_back('5');
        else if (s[i] == 'm' || s[i] == 'n' || s[i] == 'o')
            temp.push_back('6');
        else if (s[i] == 'p' || s[i] == 'q' || s[i] == 'r' || s[i] == 's')
            temp.push_back('7');
        else if (s[i] == 't' || s[i] == 'u' || s[i] == 'v')
            temp.push_back('8');
        else
            temp.push_back('9');
    }

    // Return the numeric representation.
    return temp;
}

int main()
{
    string s = "geeksquiz";

    cout << printNumber(s);

    return 0;
}
Java
class GFG {

    static String printNumber(String s)
    {

        // Stores the resultant numeric string.
        StringBuilder temp = new StringBuilder();

        // Traverse each character of the string.
        for (int i = 0; i < s.length(); i++) {

            // Map characters to their corresponding keypad
            // digit.
            if (s.charAt(i) == 'a' || s.charAt(i) == 'b'
                || s.charAt(i) == 'c')
                temp.append('2');
            else if (s.charAt(i) == 'd'
                     || s.charAt(i) == 'e'
                     || s.charAt(i) == 'f')
                temp.append('3');
            else if (s.charAt(i) == 'g'
                     || s.charAt(i) == 'h'
                     || s.charAt(i) == 'i')
                temp.append('4');
            else if (s.charAt(i) == 'j'
                     || s.charAt(i) == 'k'
                     || s.charAt(i) == 'l')
                temp.append('5');
            else if (s.charAt(i) == 'm'
                     || s.charAt(i) == 'n'
                     || s.charAt(i) == 'o')
                temp.append('6');
            else if (s.charAt(i) == 'p'
                     || s.charAt(i) == 'q'
                     || s.charAt(i) == 'r'
                     || s.charAt(i) == 's')
                temp.append('7');
            else if (s.charAt(i) == 't'
                     || s.charAt(i) == 'u'
                     || s.charAt(i) == 'v')
                temp.append('8');
            else
                temp.append('9');
        }

        // Return the numeric representation.
        return temp.toString();
    }

    public static void main(String[] args)
    {

        String s = "geeksquiz";

        System.out.println(printNumber(s));
    }
}
Python
def printNumber(s):
    # Stores the resultant numeric string.
    temp = ""

    # Traverse each character of the string.
    for i in range(len(s)):
        # Map characters to their corresponding keypad digit.
        if s[i] == 'a' or s[i] == 'b' or s[i] == 'c':
            temp += '2'
        elif s[i] == 'd' or s[i] == 'e' or s[i] == 'f':
            temp += '3'
        elif s[i] == 'g' or s[i] == 'h' or s[i] == 'i':
            temp += '4'
        elif s[i] == 'j' or s[i] == 'k' or s[i] == 'l':
            temp += '5'
        elif s[i] == 'm' or s[i] == 'n' or s[i] == 'o':
            temp += '6'
        elif s[i] == 'p' or s[i] == 'q' or s[i] == 'r' or s[i] == 's':
            temp += '7'
        elif s[i] == 't' or s[i] == 'u' or s[i] == 'v':
            temp += '8'
        else:
            temp += '9'

    # Return the numeric representation.
    return temp


if __name__ == '__main__':
    s = "geeksquiz"
    print(printNumber(s))
C#
using System;

class GFG {
    static string printNumber(string s)
    {
        // Stores the resultant numeric string.
        string temp = "";

        // Traverse each character of the string.
        for (int i = 0; i < s.Length; i++) {
            // Map characters to their corresponding keypad
            // digit.
            if (s[i] == 'a' || s[i] == 'b' || s[i] == 'c')
                temp += '2';
            else if (s[i] == 'd' || s[i] == 'e'
                     || s[i] == 'f')
                temp += '3';
            else if (s[i] == 'g' || s[i] == 'h'
                     || s[i] == 'i')
                temp += '4';
            else if (s[i] == 'j' || s[i] == 'k'
                     || s[i] == 'l')
                temp += '5';
            else if (s[i] == 'm' || s[i] == 'n'
                     || s[i] == 'o')
                temp += '6';
            else if (s[i] == 'p' || s[i] == 'q'
                     || s[i] == 'r' || s[i] == 's')
                temp += '7';
            else if (s[i] == 't' || s[i] == 'u'
                     || s[i] == 'v')
                temp += '8';
            else
                temp += '9';
        }

        // Return the numeric representation.
        return temp;
    }

    static void Main()
    {
        string s = "geeksquiz";

        Console.WriteLine(printNumber(s));
    }
}
JavaScript
function printNumber(s)
{
    // Stores the resultant numeric string.
    let temp = "";

    // Traverse each character of the string.
    for (let i = 0; i < s.length; i++) {
        // Map characters to their corresponding keypad
        // digit.
        if (s[i] === "a" || s[i] === "b" || s[i] === "c")
            temp += "2";
        else if (s[i] === "d" || s[i] === "e"
                 || s[i] === "f")
            temp += "3";
        else if (s[i] === "g" || s[i] === "h"
                 || s[i] === "i")
            temp += "4";
        else if (s[i] === "j" || s[i] === "k"
                 || s[i] === "l")
            temp += "5";
        else if (s[i] === "m" || s[i] === "n"
                 || s[i] === "o")
            temp += "6";
        else if (s[i] === "p" || s[i] === "q"
                 || s[i] === "r" || s[i] === "s")
            temp += "7";
        else if (s[i] === "t" || s[i] === "u"
                 || s[i] === "v")
            temp += "8";
        else
            temp += "9";
    }

    // Return the numeric representation.
    return temp;
}

// Driver Code
let s = "geeksquiz";
console.log(printNumber(s));

Output
433577849
Comment