Remove dictionary words from a character stream as they appear
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Feb 2026. It tests strings, tries and stacks.
Characters arrive one at a time. You keep the characters seen so far, and whenever they end with a word from a given dictionary, that word is removed at once. A removal can bring a new match into view (the characters before it plus later ones), and that match is removed too when it completes. Return what is left after the stream ends.
Interface
Unless you agree on a different interface with the interviewer, assume:
StreamCleaner(words: list[str])-
push(ch: str) -> None— appends a character and removes any dictionary word that the kept text now ends with, repeating while a removal exposes another match. -
text() -> str— the characters currently kept.
Example
words = ["abc"], stream "aabcbc"
a, a, b, c -> "aabc" ends with "abc" -> "a"
b, c -> "abc" -> ""
text() -> ""
words = ["ab", "cd"], stream "cabdx"
c, a, b -> "cab" ends with "ab" -> "c"
d -> "cd" -> ""
x -> "x"
Constraints
- Up to 10^6 characters in the stream; the dictionary holds up to 10^4 words with total length up to 10^5.
- Each
pushshould be cheap: close to O(1) amortized, not proportional to the kept text or the dictionary.
Clarifying questions
- If two words both match at the same moment (one a suffix of the other), which is removed?
- Can one removal expose another match without a new character arriving?
- Is the kept text needed after every character, or only at the end?
What a strong answer covers
- The naive check of every word against the end of the text: O(total word length) per character.
- A trie of reversed words, walked back from the end of the kept text: O(longest word) per character.
- The better structure: an Aho-Corasick automaton, and a stack holding the kept characters together with the automaton state after each one. A match pops the word's length off the stack, and the state on the new top is exactly where matching resumes, so nothing is rescanned.
- Amortized cost: each character is pushed and popped at most once.
- A stated rule for overlapping matches (for example, the longest word ending here), and tests for cascades.
Follow-ups
- Return the positions in the original stream of each removed word.
- Words can be added to the dictionary while the stream is running.
- The kept text is too large for memory: what must you keep to stay correct?
Where it's asked
- Google · Onsite coding · Last asked Feb 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
strings · tries · stacks
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
