Stream of Characters

Hard · Tries · Array · String · Design · Trie · Data Stream

Problem

Design a checker that receives letters one at a time and reports whether the stream just finished spelling one of a set of words.

Implement StreamChecker:

The tests replay a sequence of calls: ops names each call and vals holds its arguments; the output lists what each call returns (null for the constructor).

Examples

Input: ops = ["StreamChecker","query","query","query","query","query"], vals = [[["ok","book","e"]],["b"],["o"],["o"],["k"],["e"]]
Output: [null,false,false,false,true,true]

After "book" both "book" and "ok" are suffixes; after "booke" the suffix "e" matches.

Input: ops = ["StreamChecker","query","query","query"], vals = [[["xyz"]],["x"],["y"],["z"]]
Output: [null,false,false,true]

Only when the stream reads "xyz" does a word end.

Input: ops = ["StreamChecker","query","query","query","query","query","query","query","query","query","query","query","query"], vals = [[["cd","f","kl"]],["a"],["b"],["c"],["d"],["e"],["f"],["g"],["h"],["i"],["j"],["k"],["l"]]
Output: [null,false,false,false,true,false,true,false,false,false,false,false,true]

Matches at "d" (cd), "f" and "l" (kl); a word can reach back over letters received earlier.

Constraints

Approaches

Follow-up

Only the last L letters can matter, so a ring buffer of size L bounds memory however long the stream runs. To report every match rather than a yes or no, the Aho-Corasick automaton finds all words ending at each letter in time proportional to the matches; the use cases count the words ending at each letter and report the longest.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…