Convert a sentence into its mobile numeric keypad sequence

Easy

Problem

On an old phone keypad, a letter is typed by pressing its key repeatedly (a = 2, b = 22, c = 222, …, s = 7777, z = 9999), and a space is 0. Convert an uppercase sentence into its key sequence.

Example 1

Input:  "GEEKS"
Output: "43333557777"

Also asked as: Convert a Sentence into its equivalent mobile numeric keypad sequence

Test cases

Case 1

Input:    "GEEKS"
Expected: "43333557777"

Case 2

Input:    "HELLO WORLD"
Expected: "4433555555666096667775553"

Case 3

Input:    "A"
Expected: "2"

Case 4

Input:    ""
Expected: ""

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Lookup table

Time O(n)Space O(1)

Map each letter to its key presses (a→2, b→22, …); concatenate.

function keypadSequence(sentence) {
const keys = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz'];
const map = {};
for (let d = 2; d <= 9; d++)
[...keys[d]].forEach((ch, i) => (map[ch] = String(d).repeat(i + 1)));
return [...sentence.toLowerCase()].map((c) => (c === ' ' ? '0' : map[c] || '')).join('');
}