KatInterview

Words Spelled by a Finger Trace Across Keys

StringsAuto-graded · 21 test cases
MediumAuto-gradedStringsstringssubsequencegreedy

Last 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 every j.
  • 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) <= 2000
  • 1 <= len(dictionary) <= 10000
  • 1 <= len(w) <= 30 for every word w
  • The total number of letters over all words is at most 200000.
  • The trace and all words contain only lowercase letters a to z.
  • dictionary may 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.