Build a trie from the banned list: each node has a map from a character to a child, and a flag for "an entry ends here". Inserting a word walks or creates one node per character, so entries with the same beginning share a path. For exact single words a Set would do the job; the trie is worth it because you can walk it while reading the text: from each position in a comment, follow the characters down the trie, stop as soon as there's no child, and report a match whenever you pass an end flag. That finds multi-word phrases and gives positions, in O(n × L) for text of length n and longest entry L. Normalise case on both sides, and check word boundaries, or scam matches inside scampi. For a true stream, where an entry can be split across chunks, add failure links (Aho-Corasick) so each character is read once and the state carries over between chunks.
Given a stream of comments, detect inappropriate language. Requires a trie data structure.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
insert creates a path of nodes, one per character, and marks the last one. walk follows a string down the trie; has asks whether that path ends on a marked node, startsWith only whether the path exists. The filter splits a comment into words and looks each one up, so camera isn't flagged for containing cam. Its limit is the last check: an entry such as free money is never a single word, so it's never found.
// A trie stores words letter by letter: words that share a beginning share a path.class Trie {constructor(words = []) {this.root = { next: new Map(), end: false };for (const word of words) this.insert(word);}insert(word) {let node = this.root;for (const ch of word.toLowerCase()) {if (!node.next.has(ch)) node.next.set(ch, { next: new Map(), end: false });node = node.next.get(ch);}node.end = true;}// The node reached by following `text`, or undefined if the path runs out.walk(text) {let node = this.root;for (const ch of text.toLowerCase()) {node = node.next.get(ch);if (!node) return undefined;}return node;}has(word) {return this.walk(word)?.end === true;}startsWith(prefix) {return this.walk(prefix) !== undefined;}}// Split the comment into words and look each one up.function flagged(comment, trie) {return (comment.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? []).filter((word) => trie.has(word));}
passes 7 checks run on every build, against the native method where there is one
- trie: has finds whole entries only
- trie: startsWith answers for prefixes
- trie: letter case is ignored, and entries share their beginnings
- flags the banned words of a comment, in order
- a banned word inside a longer word isn't flagged
- a stream is one comment after another
- the weakness: an entry with a space in it is never found
Start at every position of the comment and walk the trie with the characters that follow. The walk stops at the first character with no child, so most positions cost one lookup. Every marked node passed is a match, which is how both spam and spammer are considered at the same position. With wholeWords, a match must begin at the start of a word and end at the end of one; turning it off shows the false positives it prevents (scampi).
// Scanning the text itself, a letter at a time, is where the trie earns its place: it finds// phrases with spaces in them, and reports where each match is.class Trie {constructor(words = []) {this.root = { next: new Map(), end: false };for (const word of words) this.insert(word);}insert(word) {let node = this.root;for (const ch of word.toLowerCase()) {if (!node.next.has(ch)) node.next.set(ch, { next: new Map(), end: false });node = node.next.get(ch);}node.end = true;}// The node reached by following `text`, or undefined if the path runs out.walk(text) {let node = this.root;for (const ch of text.toLowerCase()) {node = node.next.get(ch);if (!node) return undefined;}return node;}has(word) {return this.walk(word)?.end === true;}startsWith(prefix) {return this.walk(prefix) !== undefined;}}function findBanned(text, trie, { wholeWords = true } = {}) {const lower = text.toLowerCase();const isWordChar = (ch) => ch !== undefined && /[\p{L}\p{N}]/u.test(ch);const found = [];for (let start = 0; start < lower.length; start++) {// A whole-word match can't begin in the middle of a word.if (wholeWords && isWordChar(lower[start - 1])) continue;let node = trie.root;for (let i = start; i < lower.length; i++) {node = node.next.get(lower[i]);if (!node) break; // no banned entry continues this wayif (node.end && !(wholeWords && isWordChar(lower[i + 1]))) {found.push({ match: text.slice(start, i + 1), start });}}}return found;}
passes 8 checks run on every build, against the native method where there is one
- trie: has finds whole entries only
- trie: startsWith answers for prefixes
- trie: letter case is ignored, and entries share their beginnings
- finds words and phrases, with where they start
- whole words only, by default
- an entry that begins another: both are checked, the right one matches
- wholeWords: false matches inside words too (and shows why that's risky)
- letters with accents count as part of a word
The scan above restarts for every position and needs the whole text. Aho-Corasick adds a fail link to each node: where to continue when the next character doesn't fit, without rereading anything. The filter then keeps one state and advances it per character, so text can arrive in chunks of any size and an entry split across two chunks is still found. out links report shorter entries that end at the same character. It reads each character once: O(n + matches). It matches inside words, so apply the word-boundary rule to its results if that's what you need.
// A stream arrives in chunks, and a word can be split across two of them. Aho-Corasick turns// the trie into a machine that reads each character once and never backs up: every node gets a// `fail` link to the longest shorter entry-prefix that ends at the same place.class StreamFilter {constructor(words) {const make = () => ({ next: new Map(), fail: null, word: null, out: null });this.root = make();for (const word of words) {let node = this.root;for (const ch of word.toLowerCase()) {if (!node.next.has(ch)) node.next.set(ch, make());node = node.next.get(ch);}node.word = word.toLowerCase();}// Breadth-first, so a node's fail target (which is shallower) is finished before it's needed.const queue = [];for (const child of this.root.next.values()) {child.fail = this.root;queue.push(child);}for (let head = 0; head < queue.length; head++) {const node = queue[head];for (const [ch, child] of node.next) {let f = node.fail;while (f !== this.root && !f.next.has(ch)) f = f.fail;child.fail = f.next.get(ch) ?? this.root;// `out`: the nearest entry that also ends here (a shorter word inside this one).child.out = child.fail.word ? child.fail : child.fail.out;queue.push(child);}}this.state = this.root;this.position = 0; // characters read so far, across all chunks}// Feed the next piece of the stream; returns the entries that END in this piece.feed(chunk) {const found = [];for (const ch of chunk.toLowerCase()) {while (this.state !== this.root && !this.state.next.has(ch)) this.state = this.state.fail;this.state = this.state.next.get(ch) ?? this.root;this.position++;for (let node = this.state.word ? this.state : this.state.out; node; node = node.out) {found.push({ word: node.word, end: this.position });}}return found;}reset() {this.state = this.root;this.position = 0;}}
passes 7 checks run on every build, against the native method where there is one
- finds every entry in one pass, overlapping ones included
- a word split across chunks is still found
- one character at a time gives the same matches as one big chunk
- after a failed match it falls back without rereading
- agrees with a plain search on every position
- reset starts a new stream
- nothing banned, nothing found
Autocomplete
The same structure answers "which entries start with what the user has typed": walk to the prefix's node and list everything below it.
Matching many patterns at once
Aho-Corasick is the standard way to search a text for a whole dictionary in one pass, used in content filters and intrusion detection.
The Scunthorpe problem
Filters that match inside words block innocent text: the town of Scunthorpe is the famous case. Word boundaries and allow lists are the usual defence.
Checking each banned word with
comment.includes(word): one pass over the text per word, and it matches inside other words.Forgetting the end-of-entry flag, so every prefix of a banned word counts as banned.
Comparing case-sensitively, or lower-casing only one side.
Stopping at the first match from a position, which misses
spammerafter findingspam.No word-boundary rule, so
camblockscamera.Scanning each chunk of a stream on its own, which misses an entry split across two chunks.
Why a trie and not a Set?
For whole single words a Set is simpler and just as fast. The trie adds prefix walking: you can scan text character by character, match phrases, stop early when no entry continues, and extend it with failure links for a single pass.
How do you handle l33t spelling and spacing tricks?
Normalise before matching: fold case, strip accents with Unicode normalisation, map look-alike characters (0 to o, @ to a), and collapse repeated letters. Each step also raises the false-positive rate, so pair it with an allow list and human review.
How much memory does the trie use?
One node per distinct prefix, each with a Map. For a large dictionary, arrays indexed by character code or a compressed (radix) trie that merges single-child chains cut that down.
What's the cost per comment?
The position-by-position scan is O(n × L) in the worst case for a comment of length n and longest entry L. Aho-Corasick is O(n + matches) after building the links once in time proportional to the total length of the dictionary.
- en.wikipedia.org/wiki/Trie
- en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm
- en.wikipedia.org/wiki/Scunthorpe_problem
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize