Python coding

Words ending in a letter stream

Letters arrive one at a time. Write a class StreamWatcher, built from a list words, with a method push(letter): it receives the next letter and returns True if the letters received so far end with some word of words (the latest letters, read in order, spell that word), otherwise False.

Words use lowercase a–z and have 1 to 20 letters; words may be empty or contain repeats, and the stream uses lowercase a–z too. Each push should cost O(length of the longest word), not a check of every word.

The tests call the provided run_watcher(words, stream): it builds your class and returns the result of push for each letter of stream, in order.

Besides the tests, one large input (2,000 words, 7,000 letters) with a ~250 ms limit (scaled to your device's speed): brute force won't pass.

  • run_watcher(["at","q","rst"], "matqrst") → [false,false,true,true,false,false,true]
  • run_watcher(["he","she","hers"], "ushers") → [false,false,false,true,false,true]
  • run_watcher([], "abc") → [false,false,false]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Comparing every word with the end of the stream costs O(number of words) per letter. A trie tests all the words at once, if it reads the letters in the order you get them.

Hint 2

A word that just ended is read from its last letter, which is the newest one. So insert every word reversed, and on push walk that trie from the newest letter back through older ones.

Hint 3

Return True at the first end mark you meet and False at the first missing child. Only the last L letters can matter, L being the longest word's length, so keep just those.

Solution and why it works
pythonO(total letters of words) to build, O(M) per push, M = longest word · O(total letters of words)
# --- your code ---
from collections import deque


class StreamWatcher:
    def __init__(self, words: list[str]) -> None:
        self.root = {}                   # a trie of the words spelled backwards
        for w in words:
            node = self.root
            for ch in reversed(w):
                node = node.setdefault(ch, {})
            node["$"] = True
        self.recent = deque(maxlen=max(map(len, words), default=0))    # older letters can't matter

    def push(self, letter: str) -> bool:
        self.recent.appendleft(letter)   # newest letter first, the order the reversed trie reads
        node = self.root
        for ch in self.recent:
            node = node.get(ch)
            if node is None:
                return False             # no word ends with these latest letters
            if "$" in node:
                return True              # a whole word just ended at the newest letter
        return False


# --- provided: do not edit ---
def run_watcher(words: list[str], stream: str) -> list[bool]:
    watcher = StreamWatcher(words)
    return [watcher.push(ch) for ch in stream]

A word ending at the newest letter is a path that starts at that letter and runs backwards, so the trie stores the words reversed and each push walks it from the newest letter: the first end mark means a match, a missing child means none. That is at most as many steps as the longest word has letters, however many words there are. The trap is a forward trie with a single pointer: after a mismatch it restarts too late and misses overlaps such as "aab" in "aaab".