Predictive text for a phone keypad
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in SpaceXAI's onsite applied coding round, last asked Jun 2025. It tests trie, strings and search.
Build predictive text for a classic phone keypad. Each digit from 2 to 9 stands for a group of letters (2 = abc, 3 = def, 4 = ghi, 5 = jkl, 6 = mno, 7 = pqrs, 8 = tuv, 9 = wxyz); 0 and 1 have none. A word's encoding replaces each letter with its digit, so "cat" is "228". Given a dictionary and the keys a user has pressed so far, return every word whose encoding starts with those keys.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
suggestions(words: list[str], queries: list[str]) -> list[list[str]]— for each query (a non-empty digit string), the matching words in ascending lexicographic order, or[].
Example
words = ["cat", "bat", "act", "car", "care", "dog"]
"228" -> ["act", "bat", "cat"] # all encode to 228
"22" -> ["act", "bat", "car", "care", "cat"] # prefix of 228, 227, 2273
"2273" -> ["care"]
"364" -> ["dog"]
"9" -> []
A query containing 0 or 1 matches nothing.
Constraints
- Up to 10^5 distinct lowercase words of length 1–20; up to 10^4 queries of length 1–20.
- At most 10^6 words returned in total.
- Preprocess once; don't rescan every word per query.
Clarifying questions
- Exact encoding match, or prefix match (suggesting longer words)?
- How should results be ordered: alphabetically, or by word frequency?
- Should results be capped?
- What do
0and1do?
What a strong answer covers
- Encoding each word once and building a trie over digit strings, with each node holding the words in its subtree, or a sorted list of
(encoding, word)pairs searched by prefix range. - Query cost O(len(query) + output); sorting results once at build time.
- Memory trade-off of storing word lists at every node versus collecting on demand.
- Tests for
0/1, a query longer than every word, and shared encodings.
Follow-ups
- Rank suggestions by frequency and return the top 3.
- Support adding words the user types.
- The user may have pressed one wrong key.
Where it's asked
- SpaceXAI · Onsite applied coding · Last asked Jun 2025Two or three rounds, in person (Palo Alto for many roles)
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
