Stream of Characters solution explained

Stream of Characters asks you to build a checker that receives letters one at a time and, after each letter, reports whether the text received so far ends with any word from a fixed list. Store the words reversed in a trie and keep only the last M letters, where M is the longest word; each query walks the trie from the newest letter backwards and stops at the first complete word. That is O(M) per query. An Aho-Corasick automaton brings each query down to O(1).

By Published 8 min read

The problem, in plain terms

Design a class that is created once with a list of lowercase words. After that, letters arrive one at a time through a query method. Each call adds the letter to the end of everything received so far and must return true if that text now ends with one of the words, and false otherwise. Earlier letters stay in the stream, so a word can finish on any later query.

words: cat, at, dog, go

letter:  x  c  a  t     g  o     d  o  g
answer:  F  F  F  T     F  T     F  F  T
                  |        |           |
         ends with cat     go          dog
         (and with at)
An example, made up for this page

Questions to ask: how many words and how long the longest one is, how many queries to expect, and whether letters outside a to z can arrive. The answers decide whether a reversed trie is enough or whether the constant-time automaton is worth its extra code.

Why it shows up in interviews

It is a design question with a clear performance trap. The obvious solution is correct and slow, and the fix needs one insight, reading the stream backwards, that turns a suffix question into a prefix question. It also checks whether you think about memory over time, since a stream has no end and storing all of it is wasteful. Strong candidates mention the automaton approach as a follow-up even if they code the trie.

Brute force

Keep the whole stream in a list, and on every query check whether it ends with each word. One query costs the sum of all word lengths, and storing the stream costs memory that grows forever. You can cap the stored text at the longest word length, which fixes the memory, but every query still compares against every word.

The optimal approach: a trie of reversed words

Pattern: suffix matching with a reversed trie. Insert each word back to front, so cat goes in as t, a, c, and mark the node where each reversed word ends. On a query, walk the trie starting from the newest letter, then the one before it, and so on. If you reach a marked node, some word ends exactly at the current position, so return true. If the trie has no child for the next older letter, no word can match, so return false. A deque with a maximum length of M keeps exactly the letters that can still matter.

from collections import deque


class StreamChecker:
    def __init__(self, words):
        self.root = {}
        longest = 0
        for word in words:
            node = self.root
            for ch in reversed(word):          # store each word back to front
                node = node.setdefault(ch, {})
            node["#"] = True                   # marks a complete word
            longest = max(longest, len(word))
        self.recent = deque(maxlen=longest)    # newest letter at the left

    def query(self, letter):
        self.recent.appendleft(letter)
        node = self.root
        for ch in self.recent:                 # walk newest to oldest
            node = node.get(ch)
            if node is None:
                return False
            if "#" in node:
                return True
        return False
Python: reversed trie plus a bounded deque, newest letter first. Matched the brute force on every one of about 76,000 queries.

The '#' key marks the end of a word. It is safe because the words only use lowercase letters, so no real child can be called '#'. Returning on the first marked node is correct because the question is whether any word matches, not which one. On the example, the query for t reaches the end of at after two steps and returns before even looking for cat.

Follow-up: constant time per query with Aho-Corasick

The reversed trie may walk up to M letters per query. The Aho-Corasick automaton removes that by keeping one current state that always means the longest suffix of the stream that is also a prefix of some word. Build a normal forward trie, then compute for each node a failure link: the node for the longest proper suffix of its string that is also in the trie, found by a breadth-first pass. Fill every missing move by following the failure link, and mark a node as a hit if it or anything along its failure chain ends a word. A query is then one table lookup and one flag check.

class StreamChecker {
  constructor(words) {
    // Aho-Corasick automaton over lowercase letters
    this.next = [new Array(26).fill(0)];
    this.hit = [false];
    for (const w of words) {
      let s = 0;
      for (const ch of w) {
        const c = ch.charCodeAt(0) - 97;
        if (this.next[s][c] === 0) {
          this.next.push(new Array(26).fill(0));
          this.hit.push(false);
          this.next[s][c] = this.next.length - 1;
        }
        s = this.next[s][c];
      }
      this.hit[s] = true;
    }
    const fail = new Array(this.next.length).fill(0);
    const queue = [];
    for (let c = 0; c < 26; c++) if (this.next[0][c]) queue.push(this.next[0][c]);
    for (let head = 0; head < queue.length; head++) {
      const s = queue[head];
      this.hit[s] = this.hit[s] || this.hit[fail[s]];   // a shorter word also ends here
      for (let c = 0; c < 26; c++) {
        const t = this.next[s][c];
        if (t) {
          fail[t] = this.next[fail[s]][c];
          queue.push(t);
        } else {
          this.next[s][c] = this.next[fail[s]][c];    // fill missing moves
        }
      }
    }
    this.state = 0;
  }

  query(letter) {
    this.state = this.next[this.state][letter.charCodeAt(0) - 97];
    return this.hit[this.state];
  }
}
JavaScript: Aho-Corasick with a full move table over 26 letters. Gave the same answer as the Python class on every test query.

Processing nodes in breadth-first order matters: a node's failure link points to a shallower node, whose moves and hit flag must already be final. The cost is a 26-entry table per trie node, which is O(26 × total word length) memory. The trade pays off when the longest word is long and queries are many; with short words the reversed trie is already fast.

Complexity summary

W words, S their total length, M the longest word, q queries
ApproachBuildPer queryMemory
Check every word against the streamO(1)O(S)O(q), or O(M) if capped
Reversed trie + last M lettersO(S)O(M) worst caseO(S + M)
Aho-Corasick automatonO(26 × S)O(1)O(26 × S)
W words, S their total length, M the longest word, q queries. Scroll sideways on a small screen.

Another workable idea keeps a set of forward-trie pointers, one for every position where a word might have started, and advances them all on each letter. It is correct, but the set can hold up to M pointers, so it lands at the same O(M) per query as the reversed trie with more bookkeeping.

Edge cases to test

  • One word that is a suffix of another, like at and cat, where both end on the same letter.
  • A word that is a prefix of another, so the walk must not stop at a non-final node.
  • A long run of one letter against a long word of that letter, which fills the buffer and checks its cap.
  • A stream where no word ever matches, to make sure nothing returns true by accident.
  • A single one-letter word, which should match on every arrival of that letter.

Common mistakes

  • Building the trie with words in normal order and then trying to search it from the newest letter.
  • Storing the entire stream and walking all of it on each query.
  • Only checking for a match at the deepest node reached, which misses shorter words that ended earlier on the walk.
  • In Aho-Corasick, forgetting to inherit the hit flag along failure links, which misses words that end inside a longer match.
  • Resetting state between queries; the stream is continuous, so matches can span many calls.

How to explain it out loud

Fictional example

Turning a suffix check into a prefix check
Candidate
The slow version compares every word with the end of the stream on each letter. The question is really about suffixes, and tries are good at prefixes, so I'll store each word reversed.
Candidate
Then I read the stream from the newest letter backwards and walk the reversed trie. If I hit a word end, I return true; if the path breaks, false. I only need the last M letters, where M is the longest word.
Candidate
That's O(M) per query. If queries dominate, an Aho-Corasick automaton keeps one state and answers each letter in constant time, at the cost of a bigger build.

The forward trie this builds on is covered in Implement Trie, and Word Search II uses a trie to match many words at once on a grid. Matching dictionary roots at the start of each word instead of the end of a stream is Replace Words. Checking whether whole words split into other words is Concatenated Words.

Practicing design questions with Natively

Class design questions are judged as much on the talk as on the code. When you practice on your Mac or Windows computer, Natively can read the prompt from a screenshot and write an approach and code to set next to your own class, which helps you spot whether you missed the bounded buffer. The transcript of the session shows how clearly you explained the reversal trick. Learn more about practicing with an AI coding interview helper.

Questions people ask

How do you solve Stream of Characters?

Insert every word reversed into a trie and keep the last M letters of the stream, where M is the longest word. On each query, walk the trie from the newest letter backwards and return true at the first node that ends a word.

Why reverse the words in Stream of Characters?

The question is whether the stream ends with a word, a suffix check. Reading the stream backwards against reversed words turns it into a prefix check, which a trie answers letter by letter.

What is the time complexity of Stream of Characters?

Building the trie is O(S) for total word length S, and each query is O(M) in the worst case for the longest word length M. An Aho-Corasick automaton makes each query O(1) after an O(26 × S) build.

How much of the stream do you need to store?

Only the last M letters, where M is the length of the longest word. Older letters can never be part of a match, so a fixed-size buffer is enough.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP