Keep three pieces of state: the text so far, which key was pressed last, and when. On a press, look up the key's letters. If it's the same key as last time and less than the window (say one second) has passed, this press cycles: move to the key's next letter, wrapping after the last one, and replace the last character of the text. Otherwise it appends the key's first letter. Then record the key and the time. So 2, 2 gives b, a pause then 2 gives ba, and 6 gives bam immediately, since a different key never waits. For a real UI the pause is a timer that's restarted on every press: when it fires, the letter is committed and the cursor can move on. Mention the keys with four letters (7 and 9), and what a key with no letters should do.
Implement a number/character pad like old flip phones — buttons where 2 = abc, 3 = def, etc. Pressing the same key cycles through letters within a short time window; after a delay, the next press appends. e.g. press 2 → a, press 2 again → b, wait 1s and press 2 → ba, press 6 → bam.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
No timer is needed to get the right text: comparing Date.now() with the time of the previous press decides between cycling and appending. Cycling replaces the last character using index, which wraps with % so a fourth press of 2 returns to a. The window is measured from the most recent press, so slow steady presses keep cycling as long as each gap is under a second, and a gap of exactly one second starts a new letter.
const KEYS = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz', 0: ' ' };// Pressing the key you pressed last, soon enough, replaces the last letter with the key's next// one. Any other press (another key, or the same key after the pause) adds a new letter.class Keypad {constructor(windowMs = 1000) {this.windowMs = windowMs;this.text = '';this.lastKey = null;this.lastAt = -Infinity;this.index = 0; // which of the key's letters is showing}press(key) {key = String(key);const letters = KEYS[key];if (!letters) return this.text; // a key with no letters does nothingconst now = Date.now();if (key === this.lastKey && now - this.lastAt < this.windowMs) {this.index = (this.index + 1) % letters.length; // after the last letter, back to the firstthis.text = this.text.slice(0, -1) + letters[this.index];} else {this.index = 0;this.text += letters[0];}this.lastKey = key;this.lastAt = now;return this.text;}}
passes 8 checks run on every build, against the native method where there is one
- the example: 2 → a, 2 → b, wait 1 s, 2 → ba, 6 → bam
- a different key never waits
- pressing past the last letter wraps to the first
- each press restarts the pause
- just inside and exactly at the pause
- 0 is a space; keys given as strings work; a key with no letters does nothing
- two keypads don't share state
- the pause length can be set
A screen has to show the moment a letter is settled, and that's an event with no key press, so the window becomes a timer. Each press restarts it; when it fires, pending turns false and onChange reports it. commit() does the same on demand (old phones had a key for it), which is how you type aa without waiting. backspace() removes a letter and ends any cycle, so the next press of the same key starts fresh.
const KEYS = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz', 0: ' ' };// A screen needs to know when a letter stops being changeable (to move the cursor on), so the// pause is a real timer. Plus what every phone had: a key to accept the letter now, and delete.class Keypad {constructor({ windowMs = 1000, onChange } = {}) {this.windowMs = windowMs;this.onChange = onChange;this.text = '';this.lastKey = null;this.index = 0;this.pending = false; // true while the last letter can still be cycledthis.timer = null;}press(key) {key = String(key);const letters = KEYS[key];if (!letters) return this.text;if (this.pending && key === this.lastKey) {this.index = (this.index + 1) % letters.length;this.text = this.text.slice(0, -1) + letters[this.index];} else {this.index = 0;this.text += letters[0];}this.lastKey = key;this.pending = true;clearTimeout(this.timer);this.timer = setTimeout(() => this.commit(), this.windowMs); // each press restarts the pausethis.changed();return this.text;}// Accept the letter now: the next press of the same key starts a new letter.commit() {clearTimeout(this.timer);this.timer = null;if (!this.pending) return;this.pending = false;this.changed();}backspace() {clearTimeout(this.timer);this.timer = null;this.pending = false;this.text = this.text.slice(0, -1);this.changed();return this.text;}changed() {if (this.onChange) this.onChange({ text: this.text, pending: this.pending });}}
passes 13 checks run on every build, against the native method where there is one
- the example: 2 → a, 2 → b, wait 1 s, 2 → ba, 6 → bam
- a different key never waits
- pressing past the last letter wraps to the first
- each press restarts the pause
- just inside and exactly at the pause
- 0 is a space; keys given as strings work; a key with no letters does nothing
- two keypads don't share state
- the pause length can be set
- onChange reports the text and whether the last letter can still change
- commit accepts the letter without waiting
- commit notifies once, and leaves no timer
- backspace removes the last letter and ends its cycle
- backspace during a cycle doesn't let the same key continue it
The string form of the problem: given the keys pressed, with a space for each pause, what was typed? decode splits the sequence into runs of the same digit; a run of length k selects letter k of that key, wrapping. encode is the reverse and inserts a pause only between two letters that share a key. The last check round-trips whole sentences through both.
const KEYS = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz', 0: ' ' };// The same rules as pure functions over a whole sequence, with a space standing for the pause:// "22 2 6" is b, a, m. Useful for tests, and it is the classic string version of this question.const PRESSES = new Map(); // letter -> the key repeated as often as needed, e.g. 'c' -> '222'for (const [key, letters] of Object.entries(KEYS)) {[...letters].forEach((letter, i) => PRESSES.set(letter, key.repeat(i + 1)));}function decode(sequence) {let text = '';for (const run of sequence.match(/(\d)\1*/g) ?? []) {const letters = KEYS[run[0]];if (!letters) throw new RangeError(`key ${run[0]} has no letters`);text += letters[(run.length - 1) % letters.length];}return text;}function encode(text) {let sequence = '';for (const ch of text.toLowerCase()) {const presses = PRESSES.get(ch);if (!presses) throw new RangeError(`no key types "${ch}"`);// Two letters on the same key need a pause between them, or they'd read as one letter.if (sequence.endsWith(presses[0])) sequence += ' ';sequence += presses;}return sequence;}
passes 6 checks run on every build, against the native method where there is one
- decode: runs of a key pick the letter; a space is the pause
- decode: wraps past the last letter, and 0 is a space
- decode: a key with no letters is an error
- encode: the fewest presses, with a pause only where it's needed
- encode: a character no key types is an error
- decode undoes encode
Multi-tap
The text entry method of phones with a 12-key pad: each key cycles through its letters, and a pause (or a different key) accepts the current one.
The letter layout
Which letters sit on which key is an international standard (ITU E.161): 2 is ABC up to 9 is WXYZ, with four letters on 7 and 9.
TV remotes and consoles
On-screen keyboards driven by a number pad or a remote still use multi-tap, and any 'press again to cycle' control (a single button stepping through modes with a timeout) has the same state machine.
Appending on every press and never replacing, so
2, 2givesaa.Measuring the window from the first press of a letter instead of the most recent one.
Making a different key wait for the pause.
Not wrapping after the last letter, which reads past the end of the key's letters.
Assuming every key has three letters: 7 and 9 have four.
Sharing the state between instances by keeping it at module level.
Leaving the commit timer running after a delete or when the component goes away.
How would you type the same letter twice?
Wait out the pause, or use a key that accepts the current letter at once (commit() here). In the sequence form that's the space: 2 2 is aa, 22 is b.
How would you add capitals and digits?
A shift key that toggles a flag applied when a letter is committed, and the digit itself as the last entry in each key's cycle (abc2), or on a long press.
How does predictive text (T9) differ?
One press per letter: the key sequence 4663 is looked up in a dictionary indexed by digit strings and offers good, home, gone. That's a trie keyed by digits.
How would you test the timing?
Pass the clock in or use fake timers, so a test advances time by exactly 999 and 1000 ms instead of sleeping.