Words Spelled by a Finger Trace Across Keys
StringsAuto-graded · 21 test casesLast updated
Find all dictionary words that fit a key trace as a start- and end-anchored subsequence where letters may reuse a key, using a next-occurrence table to match many words efficiently.
A touchscreen keyboard records a continuous finger slide as the ordered string of keys the finger crossed, from the key where it first touched down to the key where it lifted off. Given that trace and a list of candidate words, return every word the slide could have spelled.
Matching rule
Let n = len(trace). A word w of length m matches the trace if you can choose an index idx[j] in the trace for each letter w[j] so that all of the following hold:
trace[idx[j]] == w[j]for everyj.idx[0] == 0: the word begins on the key where the slide began.idx[m - 1] == n - 1: the word ends on the key where the slide ended.idx[0] <= idx[1] <= ... <= idx[m - 1]: indices never go backwards, but they may stay the same.
Because neighbouring letters may share an index, a doubled letter such as ll in hello can be produced by crossing a single l key once. It also follows that a one-letter word matches only when the whole trace is that one letter.
Output
Return each distinct matching word exactly once, sorted in ascending order by plain character comparison. If no word matches, return an empty list.
Constraints
1 <= len(trace) <= 20001 <= len(dictionary) <= 100001 <= len(w) <= 30for every wordw- The total number of letters over all words is at most
200000. - The trace and all words contain only lowercase letters
atoz. dictionarymay contain duplicate words and is in no particular order.
Examples
Example 1
Input: gesture_words('hgreasdfghjklo', ['hello', 'halo', 'hero', 'help', 'hallo', 'halo', 'hole'])
Output: ['hallo', 'halo', 'hello']
Example 2
Input: gesture_words('abcd', ['add', 'abd', 'acbd', 'a', 'abbd', 'bad'])
Output: ['abbd', 'abd', 'add']
Example 3
Input: gesture_words('a', ['a', 'aa', 'ab'])
Output: ['a', 'aa']
Hints
Hint 1
Reduce the rule to three checks: the first letters agree, the last letters agree, and the word's letters appear in the trace in order, where one trace key may serve several consecutive letters.
Hint 2
To test the ordered part, place each letter greedily at the earliest trace position that is at or after the previous letter's position. Taking the earliest option never hurts later letters.
Hint 3
Many words share one trace, so precompute for every trace position and every letter the next index where that letter occurs. Then each letter of a word costs O(1). Deduplicate the words and treat one-letter words as a special case.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The matching rule breaks into three simple parts:
- Start anchor: the word's first letter must equal
trace[0]. - End anchor: the word's last letter must equal
trace[-1]. - Order: the letters must occur in the trace in order, where consecutive letters may reuse the same index.
Part 3 is a subsequence check with repeats allowed. Test it greedily: put each letter at the earliest index that is at or after the previous letter's index and holds that letter.
Since all words are checked against the same trace, build a next-occurrence table once. nxt[i][c] is the smallest index p >= i with trace[p] == c, or n if there is none. It is filled by sweeping the trace right to left while maintaining, for each of the 26 letters, the most recent index seen. Because nxt[i] includes index i itself, a doubled letter naturally stays on the same key.
Special cases:
- A one-letter word needs index
0and indexn - 1at once, so it matches only ifn == 1and the word equals the trace. - Duplicates in the dictionary are removed by iterating over
set(dictionary), and results are collected in a set. - The answer is returned sorted.
Why it is correct
Greedy is optimal. Suppose a valid assignment idx exists. Let g[j] be the greedy position of letter j. By induction g[j-1] <= idx[j-1] <= idx[j], so idx[j] is a candidate index at or after g[j-1] holding w[j]. Greedy picks the smallest such index, hence g[j] <= idx[j]. So greedy never runs out of trace when a valid assignment exists, and if greedy fails, no assignment works.
The end anchor can always be satisfied. Greedy may put the last letter at some index below n - 1. But we have already verified w[-1] == trace[-1], so that letter can be moved to index n - 1 without breaking the non-decreasing order.
The start anchor is automatic. Since w[0] == trace[0], the first lookup from position 0 returns 0.
Complexity
- Table construction: O(26 * n) time and space.
- Matching: O(1) per letter, so O(L) overall where L is the total letter count (at most 200000), including deduplication.
- Sorting the k matches: O(k log k) comparisons, each bounded by the word length.
- Total: O(26n + L + k log k) time, O(26n + L) space.
Scanning the trace separately for every word would cost O(n) per word, which is up to about 2 * 10^7 steps. The table avoids that repeated work.
Reference solution
from typing import List
def gesture_words(trace: str, dictionary: List[str]) -> List[str]:
n = len(trace)
# nxt[i][c] = smallest p >= i with trace[p] == letter c, or n if none
nxt = [None] * (n + 1)
row = [n] * 26
nxt[n] = row[:]
for i in range(n - 1, -1, -1):
row[ord(trace[i]) - 97] = i
nxt[i] = row[:]
first, last = trace[0], trace[-1]
found = set()
for w in set(dictionary):
if len(w) == 1:
# Needs index 0 and index n-1 simultaneously.
if n == 1 and w == trace:
found.add(w)
continue
if w[0] != first or w[-1] != last:
continue
pos = 0
ok = True
for ch in w:
p = nxt[pos][ord(ch) - 97]
if p >= n:
ok = False
break
pos = p
if ok:
found.add(w)
return sorted(found)