Stream of Characters Problem
Description
LeetCode Problem 1032. Implement the StreamChecker class as follows.
- StreamChecker(words): Constructor, initialize the data structure with the given words.
- query(letter): returns true if and only if for some k >= 1, the last k characters queried (in order from oldest to newest, including this letter just queried) spell one of the words in the given list.
Words and queries will only consist of lowercase English letters.
Example:
StreamChecker streamChecker = new StreamChecker(["cd","f","kl"]); // initialize the dictionary.
streamChecker.query('a'); // return false
streamChecker.query('b'); // return false
streamChecker.query('c'); // return false
streamChecker.query('d'); // return true, because 'cd' is in the wordlist
streamChecker.query('e'); // return false
streamChecker.query('f'); // return true, because 'f' is in the wordlist
streamChecker.query('g'); // return false
streamChecker.query('h'); // return false
streamChecker.query('i'); // return false
streamChecker.query('j'); // return false
streamChecker.query('k'); // return false
streamChecker.query('l'); // return true, because 'kl' is in the wordlist
Solution
Approach: Trie of Reversed Words
After each query we must know whether some word is a suffix of the stream. Checking every word against the end of the stream would cost the total length of all words per query, which is too slow with thousands of words and queries.
Suffixes become prefixes if we read backwards. So:
- Build a trie from every word reversed:
"cd"is stored asd → c. Mark the node where each reversed word ends. - Keep every queried letter in a list
stream. - On
query(letter), append it, then walk the trie starting at the root with the stream read from the newest letter to the oldest:- if the next letter has no child, no word ends here: return
false; - if we reach a node marked as a word end, the last few letters spell that word: return
true.
- if the next letter has no child, no word ends here: return
For words = ["cd","f","kl"], after the letters a b c d the walk reads d, then c, and stops at the end of the reversed word "dc", so the answer is true.
Storing the words forwards does not work: we would not know where in the stream a match should start. Reversing them fixes the start at the newest letter. The walk is never longer than the longest word, since the trie has no deeper nodes.
Complexity: O(W) time to build the trie, where W is the total length of words, and O(m) time per query, where m is the length of the longest word. O(W + q) space for the trie and the q letters queried.
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # True if a (reversed) word ends at this node
class StreamChecker:
def __init__(self, words: List[str]):
self.root = TrieNode()
for word in words:
node = self.root
for ch in reversed(word): # store words backwards: we match from the newest letter
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
self.stream = [] # every letter queried so far
def query(self, letter: str) -> bool:
self.stream.append(letter)
node = self.root
# Walk the trie with the stream read from newest to oldest.
for i in range(len(self.stream) - 1, -1, -1):
node = node.children.get(self.stream[i])
if node is None:
return False # no word ends with these letters
if node.is_end:
return True # a word equals the last few letters
return False