{"id":"prefix-and-suffix-search","title":"Prefix and Suffix Search","difficulty":"hard","patterns":["trie"],"primaryConcept":"trie-basics","concepts":["trie-basics"],"problemForm":"advanced","companies":["Google","Amazon","Meta","Apple"],"category":"trees-graphs","executionStyle":"ops-class","compareMode":"exact","syntheticTestConfig":{"inputShape":"operations","primaryParam":"operations","sizeMetric":"op-count-plus-word-lengths","opVocabulary":[{"name":"WordFilter","arity":1,"argTypes":["string[]"],"weight":1},{"name":"f","arity":2,"argTypes":["string","string"],"weight":4}],"secondaryParam":"arguments"},"description":"Design a `WordFilter` class that receives a list of words.\n\nImplement `f(prefix, suffix)` so it returns the largest index of a word that starts with `prefix` and ends with `suffix`. If no word matches both conditions, return `-1`.","examples":[{"input":"filter = WordFilter([\"apple\"])\nfilter.f(\"a\", \"e\")","output":"0","explanation":"\"apple\" starts with \"a\" and ends with \"e\", so its index 0 is returned."},{"input":"filter = WordFilter([\"apple\", \"apply\", \"ape\"])\nfilter.f(\"ap\", \"e\")","output":"2","explanation":"\"apple\" and \"ape\" match, and \"ape\" has the larger index."},{"input":"filter = WordFilter([\"orange\", \"banana\"])\nfilter.f(\"ap\", \"e\")","output":"-1","explanation":"No word has both the requested prefix and suffix."}],"constraints":[{"id":"1-len-words-1000","text":"1 <= len(words) <= 1000"},{"id":"1-len-words-i-20","text":"1 <= len(words[i]) <= 20"},{"id":"0-len-prefix-len-suffix-20","text":"0 <= len(prefix), len(suffix) <= 20"},{"id":"words-i-prefix-and-suffix-consist-only-of-lowercase-english-lett","text":"words[i], prefix, and suffix consist only of lowercase English letters"},{"id":"at-most-1000-calls-will-be-made-to-f","text":"At most 1000 calls will be made to f"}],"starterCode":"class TrieNode:\n    def __init__(self):\n        self.children = {}\n        self.index = -1\n\nclass WordFilter:\n    def __init__(self, words: list[str]):\n        # Your code here\n        pass\n\n    def f(self, prefix: str, suffix: str) -> int:\n        # Your code here\n        pass","functionName":"WordFilter","testCases":[{"id":"1","input":{"operations":["WordFilter","f"],"arguments":[[["apple"]],["a","e"]]},"expected":[null,0],"description":"Single word match."},{"id":"2","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["apple","apply","ape"]],["ap","e"],["app","ly"],["ap","le"]]},"expected":[null,2,1,0],"description":"Return the largest matching index across overlapping words."},{"id":"3","input":{"operations":["WordFilter","f","f"],"arguments":[[["orange","banana"]],["ap","e"],["ban","na"]]},"expected":[null,-1,1],"description":"Missing prefix/suffix pair returns -1."},{"id":"4","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["test","toast","test"]],["te","st"],["to","st"],["tes","t"]]},"expected":[null,2,1,2],"description":"Duplicate words still return the latest index."},{"id":"5","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["abab","ab","baba"]],["a","b"],["ba","ba"],["ab","ab"]]},"expected":[null,1,2,1],"description":"Short words and repeated characters share composite trie paths."},{"id":"h1","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["alpha","beta"]],["","a"],["alp",""],["",""]]},"expected":[null,1,0,1],"description":"Empty prefix or suffix acts as a wildcard side."},{"id":"h2","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["a","b"]],["a","a"],["","b"],["c",""]]},"expected":[null,0,1,-1],"description":"Single-character words and a missing wildcard query."},{"id":"h4","input":{"operations":["WordFilter","f","f","f","f"],"arguments":[[["prefix","presto","prevent","suffix"]],["pre","x"],["pre","t"],["suf","x"],["pre","o"]]},"expected":[null,0,2,3,1],"description":"Several words share one prefix but differ by suffix."},{"id":"h3","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["apple","apply","ape","apex"]],["ap","e"],["app","ly"],["",""]]},"description":"The highest matching index wins for overlapping queries.","expected":[null,2,1,3]},{"id":"h5","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["a","b","ab","ba"]],["a",""],["","a"],["ab","a"]]},"description":"Empty prefix or suffix acts like a wildcard on that side.","expected":[null,2,3,-1]},{"id":"topup-wildcard-latest-index","input":{"operations":["WordFilter","f","f","f","f"],"arguments":[[["cater","cart","carbon","dog"]],["car",""],["","t"],["ca","er"],["do","g"]]},"expected":[null,2,1,0,3],"description":"Wildcard prefix or suffix queries still return the latest matching index."},{"id":"topup-repeated-character-words","input":{"operations":["WordFilter","f","f","f","f"],"arguments":[[["aa","aaa","aaaa"]],["a","aa"],["aa","a"],["aaa","aaa"],["aaaaa",""]]},"expected":[null,2,2,2,-1],"description":"Repeated characters create many prefix and suffix overlaps."},{"id":"topup-long-word","input":{"operations":["WordFilter","f","f","f"],"arguments":[[["abcdefghijklmno"]],["abc","mno"],["abcdefghijklmno","abcdefghijklmno"],["abcdefghijklmno","u"]]},"expected":[null,0,0,-1],"description":"Queries over a maximum-length word preserve exact prefix and suffix matching."},{"id":"topup-duplicates-and-empty-side","input":{"operations":["WordFilter","f","f","f","f"],"arguments":[[["level","lever","level","levitate"]],["lev","el"],["lev","er"],["","e"],["lev",""]]},"expected":[null,2,1,3,3],"description":"Duplicate words and empty-side queries both select the highest matching index."}],"hints":[{"level":1,"content":"A query has two string constraints. Think about turning the pair into one searchable key.","revealPattern":false},{"level":2,"content":"For each word, combine every suffix with the full word using a separator, then insert that composite key into a trie.","revealPattern":true},{"level":3,"content":"Store the latest word index on every node reached while inserting a composite key. Query with suffix + separator + prefix.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which implementation gives fast repeated queries?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"scan-every-word","name":"Scan every word","summary":"For each query, inspect every word and track the largest index whose prefix and suffix both match.","decisionReason":"Each f(prefix, suffix) may inspect every word and check both ends before finding the largest index. Repeated queries pay that scan again even though the word list never changes.","complexity":{"time":"O(n * m) per query","space":"O(1)"},"tradeoffs":["Runs in O(n * m) per query time and uses O(1) space."],"isOptimal":false,"steps":["Start from the largest index.","Check startswith and endswith for each word.","Return the first match, or -1."]},{"id":"composite-trie","name":"Composite-key trie","summary":"Insert every suffix + separator + word into a trie and store the latest word index along each path.","decisionReason":"For each word, inserting suffix + '#' + word records its index on every path that combines a suffix with a prefix. A query walks suffix + '#' + prefix and reads the largest index stored at that trie node.","complexity":{"time":"O(m²) preprocessing per word, O(p + s) per query","space":"O(n * m²)"},"tradeoffs":["Runs in O(m²) preprocessing per word, O(p + s) per query time and uses O(n * m²) space."],"isOptimal":true,"steps":["Create the root trie node.","For each word and each suffix, compose suffix + '#' + word.","Walk or create the composite path and write the current index.","For a query, walk suffix + '#' + prefix and return the stored index."]}]},"codingCheckpoints":[{"id":"init-root","title":"Initialize the trie root","description":"Create one root node for the composite-key trie.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"initializes_trie_root","scope":"trie-class","readMode":"tree-trie-value-query-v1"}]},"commonMistakes":["Storing words in a list instead of building an index","Creating a new root for every query"],"hint":"The constructor should allocate a single root before processing words."},{"id":"compose-key","title":"Compose suffix keys","description":"For each suffix, build a separator-delimited key that also contains the original word.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"composes_composite_trie_key","scope":"compose-key","readMode":"tree-trie-value-query-v1"}]},"commonMistakes":["Forgetting the separator","Using only the prefix or only the suffix"],"hint":"A key like suffix + '#' + word lets a query walk suffix + '#' + prefix."},{"id":"index-paths","title":"Insert composite paths","description":"Walk each composite key and create missing trie nodes as needed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"walks_or_creates_composite_trie_path","scope":"index-paths","readMode":"tree-trie-value-query-v1"}]},"commonMistakes":["Overwriting existing children unconditionally","Skipping suffixes near the end of the word"],"hint":"Every suffix from the full word down to the empty suffix should be inserted."},{"id":"store-index","title":"Store the latest index","description":"Write the current word index on the trie nodes reached by each composite key.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"stores_composite_trie_terminal_index","scope":"store-index","readMode":"tree-trie-value-query-v1"}]},"commonMistakes":["Keeping the first matching index instead of the latest","Only storing indexes outside the trie"],"hint":"Because words are processed from left to right, assigning idx as you walk keeps the largest matching index."},{"id":"query-path","title":"Walk the query path","description":"Build suffix + separator + prefix and traverse that path from the root.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"walks_composite_trie_query_path","scope":"query-path","readMode":"tree-trie-value-query-v1"}]},"commonMistakes":["Searching prefix + suffix in the wrong order","Continuing after a missing child"],"hint":"The query key mirrors the inserted composite key prefix: suffix first, then separator, then prefix."},{"id":"return-index","title":"Return index or -1","description":"Return -1 when the path is missing; otherwise return the stored index at the reached node.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"tree-trie","fact":"returns_composite_trie_terminal_index_or_miss","scope":"return-index","readMode":"tree-trie-value-query-v1"}]},"commonMistakes":["Returning a boolean instead of the index","Returning 0 when no match exists"],"hint":"A missing path is -1; a completed path returns the index stored on the current trie node."}],"slides":[{"id":"opener","chapter":"The slow way","kind":"info","eyebrow":"Understand the task","title":"Find the word with a prefix and a suffix","workspacePanel":"problem","body":["You are given a list of words and you build a WordFilter on it. Then f(prefix, suffix) must return the largest index of a word that both starts with prefix and ends with suffix. If no word satisfies both conditions, return -1.","The plain way to answer one call is to walk every word and test both ends. Watch it work, and watch what it costs when the calls keep coming."]},{"id":"brute-force","chapter":"The slow way","kind":"code-trace","eyebrow":"The obvious way","title":"Scan every word on each query","summary":"The scan returns the right index, but each query re-reads every word.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class WordFilter:\n    def __init__(self, words: list[str]) -> None:\n        self.words: list[str] = words\n\n    def f(self, prefix: str, suffix: str) -> int:\n        best: int = -1\n        for i in range(len(self.words)):\n            word: str = self.words[i]\n            prefix_matches: bool = len(word) >= len(prefix) and word[:len(prefix)] == prefix\n            suffix_matches: bool = len(word) >= len(suffix) and word[len(word) - len(suffix):] == suffix\n            if prefix_matches and suffix_matches:\n                best = i\n        return best","steps":[{"id":"scan-0","title":"Check word 0","summary":"words = [\"apple\", \"apply\", \"ape\"], prefix = \"ap\", suffix = \"e\". \"apple\" starts with \"ap\" and ends with \"e\", so it matches and best becomes 0.","codeLine":11,"state":{"s":"apple","i":0,"labels":{"s":"word"}}},{"id":"scan-1","title":"Check word 1","summary":"\"apply\" starts with \"ap\" but ends with \"y\", not \"e\". The suffix test fails, so best stays 0 and the scan keeps reading.","codeLine":11,"state":{"s":"apply","i":1,"labels":{"s":"word"}}},{"id":"scan-2","title":"Check word 2","summary":"\"ape\" starts with \"ap\" and ends with \"e\", so it matches. Because 2 is a larger index than 0, best is overwritten to 2.","codeLine":11,"state":{"s":"ape","i":2,"labels":{"s":"word"}}},{"id":"scan-return","title":"Return the largest match","summary":"Every word was read end to end and best ended on 2, the largest matching index. One query, three full words scanned.","codeLine":13,"state":{"s":"ape","i":2,"labels":{"s":"word"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class WordFilter {\n    constructor(words) {\n        this.words = words;\n    }\n\n    f(prefix, suffix) {\n        let best = -1;\n        for (let i = 0; i < this.words.length; i++) {\n            const word = this.words[i];\n            const prefixMatches = (word.length >= prefix.length) && (word.slice(0, prefix.length) === prefix);\n            const suffixMatches = (word.length >= suffix.length) && (word.slice((word.length - suffix.length)) === suffix);\n            if (prefixMatches && suffixMatches) {\n                best = i;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":3,"6":7,"7":8,"8":9,"9":10,"10":11,"11":12,"12":13,"13":16},"statementBundles":{"3":{"startLine":3,"endLine":6},"12":{"startLine":13,"endLine":15},"13":{"startLine":16,"endLine":18}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class WordFilter {\n    words: Array<string>;\n\n    constructor(words: Array<string>) {\n        this.words = words;\n    }\n\n    f(prefix: string, suffix: string): number {\n        let best = -1;\n        for (let i = 0; i < this.words.length; i++) {\n            const word = this.words[i];\n            const prefixMatches = (word.length >= prefix.length) && (word.slice(0, prefix.length) === prefix);\n            const suffixMatches = (word.length >= suffix.length) && (word.slice((word.length - suffix.length)) === suffix);\n            if (prefixMatches && suffixMatches) {\n                best = i;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":5,"6":9,"7":10,"8":11,"9":12,"10":13,"11":14,"12":15,"13":18},"statementBundles":{"3":{"startLine":5,"endLine":8},"12":{"startLine":15,"endLine":17},"13":{"startLine":18,"endLine":20}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class WordFilter {\n    List<String> words;\n\n    public WordFilter(List<String> words) {\n        this.words = words;\n    }\n\n    public int f(String prefix, String suffix) {\n        int best = -1;\n        for (int i = 0; i < this.words.size(); i++) {\n            String word = this.words.get(i);\n            boolean prefixMatches = word.length() >= prefix.length() && word.substring(0, prefix.length()).equals(prefix);\n            boolean suffixMatches = word.length() >= suffix.length() && word.substring((word.length() - suffix.length()), word.length()).equals(suffix);\n            if (prefixMatches && suffixMatches) {\n                best = i;\n            }\n        }\n        return best;\n    }\n}","lineMap":{"3":5,"6":9,"7":10,"8":11,"9":12,"10":13,"11":14,"12":15,"13":18},"statementBundles":{"3":{"startLine":5,"endLine":8},"12":{"startLine":15,"endLine":17},"13":{"startLine":18,"endLine":20}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class WordFilter\n{\n    public List<string> words;\n\n    public WordFilter(List<string> words)\n    {\n        this.words = words;\n    }\n\n    public int F(string prefix, string suffix)\n    {\n        int best = -1;\n        for (int i = 0; i < this.words.Count; i++) {\n            string word = this.words[i];\n            bool prefixMatches = word.Length >= prefix.Length && word.Substring(0, prefix.Length) == prefix;\n            bool suffixMatches = word.Length >= suffix.Length && word.Substring(word.Length - suffix.Length, (word.Length) - (word.Length - suffix.Length)) == suffix;\n            if (prefixMatches && suffixMatches) {\n                best = i;\n            }\n        }\n        return best;\n        return 0;\n    }\n}","lineMap":{"3":7,"6":12,"7":13,"8":14,"9":15,"10":16,"11":17,"12":18,"13":21},"statementBundles":{"3":{"startLine":7,"endLine":11},"12":{"startLine":18,"endLine":20},"13":{"startLine":21,"endLine":24}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct WordFilter {\n    vector<string> words;\n\n    WordFilter(vector<string> words) {\n        this->words = words;\n    }\n\n    int f(string prefix, string suffix) {\n        int best = -1;\n        for (int i = 0; i < this->words.size(); i++) {\n            string word = this->words[i];\n            bool prefix_matches = word.size() >= prefix.size() && string(word.begin() + 0, word.begin() + prefix.size()) == prefix;\n            bool suffix_matches = word.size() >= suffix.size() && string(word.begin() + (word.size() - suffix.size()), word.begin() + word.size()) == suffix;\n            if ((prefix_matches && suffix_matches)) {\n                best = i;\n            }\n        }\n        return best;\n    }\n};","lineMap":{"3":5,"6":9,"7":10,"8":11,"9":12,"10":13,"11":14,"12":15,"13":18},"statementBundles":{"3":{"startLine":5,"endLine":8},"12":{"startLine":15,"endLine":17},"13":{"startLine":18,"endLine":20}}}}},"body":["Walk every word, keep the largest index whose word both starts with prefix and ends with suffix, and return that index or -1. It is correct, but it re-reads all the words on every single call."]},{"id":"brute-force-cost","chapter":"The slow way","kind":"case-probe","eyebrow":"Count the work","title":"How much does one f call read?","summary":"There are up to n words, each up to length m, and up to 1000 calls to f.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"rescan-all","state":{"arrays":[{"name":"words (re-read every call)","values":["apple","apply","ape"]}]}}]},"options":[{"id":"all-words","label":"Up to every character of every word, about n times m per call","rationale":"The scan has no index, so it re-reads all n words and tests both ends of each, up to m characters apiece. Every one of the up to 1000 calls pays that full n times m again, even though the words never change after construction.","isCorrect":true},{"id":"two-ends","label":"Just the prefix and suffix lengths, once","rationale":"That is the cost we want, but a flat list cannot reach it. With nothing precomputed, the only way to know which word matches both ends is to try every stored word in turn.","isCorrect":false},{"id":"log-words","label":"About log n, if the words are sorted","rationale":"Sorting helps find an exact word, but a single sort cannot order by prefix and by suffix at the same time, so each call would still scan a run of words rather than reading just the two query parts.","isCorrect":false}],"answer":"About n times m per call. With words sitting in a flat list, every f re-reads all of them character by character, because nothing precomputed records which word carries which prefix and suffix. The constructor gets to run once; that is where the work should move."},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which implementation gives fast repeated queries?","workspacePanel":"trace"},{"id":"trie-node-state","kind":"case-probe","chapter":"The idea","eyebrow":"Define the nodes","title":"What does one trie node represent while a key is walked?","summary":"The current symbols are e, #, a, p.","workspacePanel":"trace","options":[{"id":"path-so-far","label":"The key prefix e#ap","rationale":"A trie node stands for the key prefix spelled by the edges from the root to that node.","isCorrect":true},{"id":"whole-word","label":"One complete word from the original list","rationale":"Many keys can pass through the same node before a full word or query path is complete."},{"id":"remaining-query","label":"The part of the query that has not been read yet","rationale":"The unread characters decide where the walk goes next; the current node represents what has already been read."}],"answer":"A trie node represents the path string consumed from the root to that node."},{"id":"monotonic-probe","chapter":"The trick","kind":"case-probe","eyebrow":"Find the structure","title":"What does one traversal need to test for a query?","summary":"A query asks two things at once: starts with prefix, ends with suffix.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"combined-key","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e","e#","e#a","e#ap"]}}}]},"options":[{"id":"one-key","label":"Glue a suffix and the full word into one key, so one walk tests both ends","rationale":"If you store every key shaped suffix + '#' + word, then walking suffix + '#' + prefix checks the ending first and the beginning second in a single path. The query never has to consult the prefix and the suffix as two separate searches.","isCorrect":true},{"id":"two-tries","label":"Keep one trie of prefixes and a separate trie of suffixes","rationale":"Two tries can each answer one end, but then you must intersect their matching index sets, which brings back per-call scanning. The win comes from a single key that encodes both ends together.","isCorrect":false},{"id":"prefix-only","label":"Store only the prefixes; check the suffix afterwards","rationale":"A prefix-only trie still leaves the suffix test to a scan of every word under that prefix, so the expensive part of the brute force survives. Both ends have to live on the same path.","isCorrect":false}],"answer":"Glue each suffix to the full word as suffix + '#' + word. Then a query walks suffix + '#' + prefix down one path, settling the ending and the beginning in a single traversal. The separator keeps the suffix from bleeding into the word."},{"id":"keep-floor-probe","chapter":"The trick","kind":"case-probe","eyebrow":"Cover every query","title":"Which suffixes of a word must you insert?","summary":"A query can ask for any suffix, like \"e\", \"le\", or \"\" of \"apple\".","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-suffixes","state":{"graph":{"nodes":[{"id":"apple","label":"apple#apple"},{"id":"pple","label":"pple#apple"},{"id":"ple","label":"ple#apple"},{"id":"le","label":"le#apple"},{"id":"e","label":"e#apple"},{"id":"empty","label":"#apple"}],"edges":[],"highlighted":["apple","pple","ple","le","e","empty"]}}}]},"options":[{"id":"every-suffix","label":"Every suffix of the word, from the full word down to the empty string","rationale":"A query's suffix can be any ending of the word, so each ending needs its own key. Inserting \"#apple\", \"e#apple\", \"le#apple\", ... up to \"apple#apple\" means whatever suffix a query names, its key was built. The empty suffix is the wildcard case where any word with the right prefix matches.","isCorrect":true},{"id":"full-only","label":"Only the full word as its own suffix","rationale":"Storing just \"apple#apple\" answers f(prefix, \"apple\") but nothing for f(\"ap\", \"e\"), whose suffix is only the ending \"e\". Every possible ending has to be reachable.","isCorrect":false},{"id":"one-char","label":"Only the single last character","rationale":"A one-character suffix handles f(\"ap\", \"e\") but not f(\"ap\", \"le\"), which asks for a two-character ending. Suffixes of every length can be queried, so every length must be inserted.","isCorrect":false}],"answer":"Insert every suffix of the word, from the empty string up to the whole word, each glued to the full word. That is what lets any suffix a query might name be found, and it is why preprocessing costs O(m squared) per word in exchange for fast lookups."},{"id":"latest-index-state","kind":"case-probe","chapter":"The idea","eyebrow":"Store the answer","title":"If two words share a query path, which index should the node keep?","summary":"words = [\"apple\", \"ape\"], and both match f(\"ap\", \"e\").","workspacePanel":"trace","options":[{"id":"latest-index","label":"The larger index written by the later matching word","rationale":"The query asks for the largest matching index, so every node on a matching path must retain the latest index seen there.","isCorrect":true},{"id":"first-index","label":"The first index that ever reached that node","rationale":"Keeping the first index would return 0 for apple even when ape at index 1 also matches."},{"id":"all-words","label":"A list of every word under the node","rationale":"A list can answer the query, but this design stores the best index directly on the path."}],"answer":"The node keeps the latest index written along that path, so ties by prefix and suffix return the largest original index."},{"id":"approach-bridge","chapter":"The trick","kind":"info","eyebrow":"Name the moves","title":"Build composite paths, then walk one per query","summary":"Two moves carry the whole design.","ctaLabel":"Trace it","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#app","label":"p"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#app"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e#app","e#ape"]}}}]},"body":["In the constructor, for each word and each of its suffixes, build the key suffix + '#' + word and walk it into a shared trie, stamping the current word index on every node you pass. Words ending alike share the front of these paths, and a later word simply overwrites the index, so the largest matching index survives.","For a query, build suffix + '#' + prefix and walk that one path from the root. If the walk ever lacks the next character, no word has both ends, so return -1; otherwise return the index stored on the node you land on."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the state","title":"Trace WordFilter([\"apple\", \"ape\"]) then f(\"ap\", \"e\")","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"insert-apple","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#app","label":"p"},{"id":"e#appl","label":"l"},{"id":"e#apple","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#app"],["e#app","e#appl"],["e#appl","e#apple"]],"current":"e#apple","highlighted":["e","e#","e#a","e#ap","e#app","e#appl","e#apple"]}}},{"id":"insert-ape","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#app","label":"p"},{"id":"e#appl","label":"l"},{"id":"e#apple","label":"e"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#app"],["e#app","e#appl"],["e#appl","e#apple"],["e#ap","e#ape"]],"current":"e#ape","highlighted":["e","e#","e#a","e#ap","e#ape"]}}},{"id":"query-walk","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#app","label":"p"},{"id":"e#appl","label":"l"},{"id":"e#apple","label":"e"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#app"],["e#app","e#appl"],["e#appl","e#apple"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e","e#","e#a"],"activeEdges":[["e","e#"],["e#","e#a"],["e#a","e#ap"]]}}},{"id":"query-return","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#app","label":"p"},{"id":"e#appl","label":"l"},{"id":"e#apple","label":"e"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#app"],["e#app","e#appl"],["e#appl","e#apple"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e#ap"]}}}]},"beats":[{"id":"insert-apple","title":"Inserting \"apple\" at index 0, what index do its nodes store?","summary":"The first word builds the key e#apple (its \"e\" suffix glued to the word).","prompt":"Walk e#apple from the root, creating nodes as needed. Word \"apple\" sits at index 0.","options":[{"id":"stamp-0","label":"Every node on the path stores 0","rationale":"As insert walks e # a p p l e, it writes the current word index onto each node it passes. \"apple\" is index 0, so every node along e#apple now carries 0.","isCorrect":true},{"id":"stamp-last","label":"Only the final node stores 0","rationale":"Storing the index only at the end would answer f(\"apple\", \"e\") but not f(\"ap\", \"e\"), whose query path stops at the \"e#ap\" node. The index has to live on every node so a shorter prefix can read it.","isCorrect":false},{"id":"stamp-none","label":"No node stores an index until a query asks","rationale":"The index is what the query returns, so it must be written during insertion. There is no word list left to consult at query time; the trie nodes are the only record.","isCorrect":false}],"answer":"Every node along e#apple stores 0. Writing the index on each node lets a query that ends at an interior node, like the \"ap\" prefix, still read a matching word's index."},{"id":"insert-ape","title":"Now insert \"ape\" at index 2. What happens at the shared \"e#ap\" node?","summary":"\"ape\" builds e#ape, which shares e # a p with \"apple\" before splitting.","prompt":"The nodes e, #, a, p already exist from \"apple\" and hold index 0. \"ape\" is index 2.","options":[{"id":"overwrite-2","label":"It reuses those nodes and overwrites their stored index with 2","rationale":"Insert follows existing children when present, so e # a p are reused, and the index write replaces 0 with 2. Because words are inserted in increasing index order, the larger index always lands last and wins, exactly the largest-match rule.","isCorrect":true},{"id":"keep-0","label":"It keeps 0, since \"apple\" was there first","rationale":"Keeping the first index would return the smaller match. The problem wants the largest index, and later words have larger indices, so the stored value must be overwritten, not preserved.","isCorrect":false},{"id":"new-branch-0","label":"It builds a fresh e#ap path so \"apple\" keeps its 0","rationale":"Duplicating the shared front would lose the overwrite and waste space. Insert reuses any child that already exists; only the diverging tail, the second \"e\" of \"ape\", is new.","isCorrect":false}],"answer":"It reuses e # a p and overwrites their index from 0 to 2, then adds the new \"e\" node for \"ape\". Processing words in index order means the largest matching index is always the last one written."},{"id":"query-walk","title":"f(\"ap\", \"e\") walks which key, and how far does it get?","summary":"The query glues suffix and prefix the same way the keys were built.","prompt":"Build the query key from suffix \"e\" and prefix \"ap\", then walk it from the root.","options":[{"id":"walk-eap","label":"It walks e#ap and reaches the \"p\" node","rationale":"The query key is suffix + '#' + prefix, so \"e\" + \"#\" + \"ap\" = e#ap. Every character has a child, so the walk lands on the e#ap node, the same shared node both matching words stamped.","isCorrect":true},{"id":"walk-ape","label":"It walks ap#e, prefix first","rationale":"Inserting put the suffix before the separator, so the query must mirror that order: suffix first, then prefix. Walking ap#e would not match any inserted key.","isCorrect":false},{"id":"walk-full","label":"It must walk all the way to a word-end node","rationale":"The query only spells suffix + '#' + prefix, which can stop at an interior node. That is fine, because every node carries the latest matching index, so an interior stop still has the answer.","isCorrect":false}],"answer":"It walks e#ap, suffix then separator then prefix, and stops on the \"e#ap\" node. The walk mirrors how keys were inserted, so the path exists exactly when some word has this prefix and suffix."},{"id":"query-return","title":"The walk landed on \"e#ap\". What does f return?","summary":"The walk completed on e#ap.","prompt":"\"apple\" wrote 0 on that path; \"ape\" later wrote 2.","options":[{"id":"return-2","label":"2, from the second write","rationale":"The node holds the latest index written during insertion, which is 2 from \"ape\". Returning it gives the largest index whose word starts with \"ap\" and ends with \"e\", matching the expected answer.","isCorrect":true},{"id":"return-0","label":"0, because \"apple\" matches too","rationale":"\"apple\" does match, but \"ape\" overwrote the node's index to 2, and 2 is the larger index. The stored value already encodes the largest match, so the answer is 2, not 0.","isCorrect":false},{"id":"return-neg1","label":"-1, since the path did not reach a word end","rationale":"-1 is only for a missing path. Here the walk completed, and every node carries a real matching index, so the node's stored value is returned rather than a miss.","isCorrect":false}],"answer":"Return 2, the index stored on the e#ap node. It is the latest write there, which is the largest index of any word matching both ends, so f(\"ap\", \"e\") is 2."}]},{"id":"return-left-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Should a node keep its first index instead of the latest?","workspacePanel":"trace","summary":"Writing the index onto a node only the first time preserves the earliest matching word. Every word is still findable. Watch what it does when two words match the same query and the larger index should win.","pitfall":"The insert below only stamps node.index when the node is still unset (-1), so an earlier, smaller index can never be replaced by a later, larger one.","whyItMatters":"Overwrite node.index every time. With \"apple\" at index 0 and \"ape\" at index 2 both ending in \"e\" and starting with \"ap\", the shared e#ap node is stamped 0 first. If insert refuses to overwrite, that 0 sticks, and f(\"ap\", \"e\") returns 0 instead of 2. Because words arrive in increasing index order, always overwriting is exactly what keeps the largest matching index.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"class TrieNode:\n    def __init__(self) -> None:\n        self.children: dict[str, TrieNode] = {}\n        self.index: int = -1\n\nclass WordFilter:\n    def __init__(self, words: list[str]) -> None:\n        self.root: TrieNode = TrieNode()\n        for idx, word in enumerate(words):\n            size: int = len(word)\n            for i in range(size + 1):\n                key: str = word[i:] + \"#\" + word\n                node: TrieNode = self.root\n                for position in range(len(key)):\n                    ch: str = key[position]\n                    if ch not in node.children:\n                        node.children[ch] = TrieNode()\n                    node = node.children[ch]\n                    if node.index == -1:\n                        node.index = idx\n\n    def f(self, prefix: str, suffix: str) -> int:\n        key: str = suffix + \"#\" + prefix\n        node: TrieNode = self.root\n        for position in range(len(key)):\n            ch: str = key[position]\n            if ch not in node.children:\n                return -1\n            node = node.children[ch]\n        return node.index","steps":[{"id":"pf-apple","title":"\"apple\" (index 0) stamps the shared nodes","codeLine":20,"summary":"Inserting e#apple walks e # a p ... and writes 0 onto each fresh node, including the shared e#ap node, which was unset.","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"]],"current":"e#ap","highlighted":["e","e#","e#a","e#ap"]}}},{"id":"pf-ape","title":"\"ape\" (index 2) reaches e#ap, but the guard blocks the write","codeLine":19,"summary":"Inserting e#ape reuses e # a p. The e#ap node already holds 0, so node.index == -1 is false and the guard skips the write. The larger index 2 never lands here.","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e#ap"],"activeEdges":[["e#a","e#ap"]]}}},{"id":"pf-wrong","title":"f(\"ap\", \"e\") returns the smaller index","codeLine":19,"summary":"The query walks e#ap to the same node and reads its index: 0. But \"ape\" at index 2 also matches and is larger, so the correct answer is 2. The first-write guard returned a stale, smaller index.","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e#ap"]}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"class TrieNode {\n    constructor() {\n        this.children = new Map();\n        this.index = -1;\n    }\n}\n\nclass WordFilter {\n    constructor(words) {\n        this.root = new TrieNode();\n        for (let idx = 0; idx < words.length; idx++) {\n            const word = words[idx];\n            const size = word.length;\n            for (let i = 0; i < (size + 1); i++) {\n                const key = (word.slice(i) + \"#\") + word;\n                let node = this.root;\n                for (let position = 0; position < key.length; position++) {\n                    const ch = key[position];\n                    if (!node.children.has(ch)) {\n                        node.children.set(ch, new TrieNode());\n                    }\n                    node = node.children.get(ch);\n                    if (node.index === -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    f(prefix, suffix) {\n        const key = (suffix + \"#\") + prefix;\n        let node = this.root;\n        for (let position = 0; position < key.length; position++) {\n            const ch = key[position];\n            if (!node.children.has(ch)) {\n                return -1;\n            }\n            node = node.children.get(ch);\n        }\n        return node.index;\n    }\n}","lineMap":{"3":3,"4":4,"8":10,"9":11,"10":13,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":22,"19":23,"20":24,"23":32,"24":33,"25":34,"26":35,"27":36,"28":37,"29":39,"30":41},"statementBundles":{"4":{"startLine":4,"endLine":9},"9":{"startLine":11,"endLine":12},"17":{"startLine":20,"endLine":21},"20":{"startLine":24,"endLine":31},"28":{"startLine":37,"endLine":38},"29":{"startLine":39,"endLine":40},"30":{"startLine":41,"endLine":43}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n    constructor() {\n        this.children = new Map();\n        this.index = -1;\n    }\n}\n\nclass WordFilter {\n    constructor(words) {\n        this.root = new TrieNode();\n        for (let idx = 0; idx < words.length; idx++) {\n            const word = words[idx];\n            const size = word.length;\n            for (let i = 0; i < (size + 1); i++) {\n                const key = (word.slice(i) + \"#\") + word;\n                let node = this.root;\n                for (let position = 0; position < key.length; position++) {\n                    const ch = key[position];\n                    if (!node.children.has(ch)) {\n                        node.children.set(ch, new TrieNode());\n                    }\n                    node = node.children.get(ch);\n                    if (node.index === -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    f(prefix, suffix) {\n        const key = (suffix + \"#\") + prefix;\n        let node = this.root;\n        for (let position = 0; position < key.length; position++) {\n            const ch = key[position];\n            if (!node.children.has(ch)) {\n                return -1;\n            }\n            const nodeValue = node.children.get(ch);\n            if (nodeValue === undefined) throw new Error(\"KeyError\");\n            node = nodeValue;\n        }\n        return node.index;\n    }\n}","lineMap":{"3":3,"4":4,"8":10,"9":11,"10":13,"11":14,"12":15,"13":16,"14":17,"15":18,"16":19,"17":20,"18":22,"19":23,"20":24,"23":32,"24":33,"25":34,"26":35,"27":36,"28":37,"29":39,"30":43},"statementBundles":{"4":{"startLine":4,"endLine":9},"9":{"startLine":11,"endLine":12},"17":{"startLine":20,"endLine":21},"20":{"startLine":24,"endLine":31},"28":{"startLine":37,"endLine":38},"29":{"startLine":39,"endLine":42},"30":{"startLine":43,"endLine":45}}}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"class TrieNode {\n    children: Map<string, TrieNode>;\n    index: number;\n\n    constructor() {\n        this.children = new Map();\n        this.index = -1;\n    }\n}\n\nclass WordFilter {\n    root: TrieNode;\n\n    constructor(words: Array<string>) {\n        this.root = new TrieNode();\n        for (let idx = 0; idx < words.length; idx++) {\n            const word = words[idx];\n            const size = word.length;\n            for (let i = 0; i < (size + 1); i++) {\n                const key = (word.slice(i) + \"#\") + word;\n                let node = this.root;\n                for (let position = 0; position < key.length; position++) {\n                    const ch = key[position];\n                    if (!node.children.has(ch)) {\n                        node.children.set(ch, new TrieNode());\n                    }\n                    node = node.children.get(ch)!;\n                    if (node.index === -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    f(prefix: string, suffix: string): number {\n        const key = (suffix + \"#\") + prefix;\n        let node = this.root;\n        for (let position = 0; position < key.length; position++) {\n            const ch = key[position];\n            if (!node.children.has(ch)) {\n                return -1;\n            }\n            node = node.children.get(ch)!;\n        }\n        return node.index;\n    }\n}","lineMap":{"3":6,"4":7,"8":15,"9":16,"10":18,"11":19,"12":20,"13":21,"14":22,"15":23,"16":24,"17":25,"18":27,"19":28,"20":29,"23":37,"24":38,"25":39,"26":40,"27":41,"28":42,"29":44,"30":46},"statementBundles":{"4":{"startLine":7,"endLine":14},"9":{"startLine":16,"endLine":17},"17":{"startLine":25,"endLine":26},"20":{"startLine":29,"endLine":36},"28":{"startLine":42,"endLine":43},"29":{"startLine":44,"endLine":45},"30":{"startLine":46,"endLine":48}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n    children: Map<string, TrieNode>;\n    index: number;\n\n    constructor() {\n        this.children = new Map();\n        this.index = -1;\n    }\n}\n\nclass WordFilter {\n    root: TrieNode;\n\n    constructor(words: Array<string>) {\n        this.root = new TrieNode();\n        for (let idx = 0; idx < words.length; idx++) {\n            const word = words[idx];\n            const size = word.length;\n            for (let i = 0; i < (size + 1); i++) {\n                const key = (word.slice(i) + \"#\") + word;\n                let node = this.root;\n                for (let position = 0; position < key.length; position++) {\n                    const ch = key[position];\n                    if (!node.children.has(ch)) {\n                        node.children.set(ch, new TrieNode());\n                    }\n                    node = node.children.get(ch)!;\n                    if (node.index === -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    f(prefix: string, suffix: string): number {\n        const key = (suffix + \"#\") + prefix;\n        let node = this.root;\n        for (let position = 0; position < key.length; position++) {\n            const ch = key[position];\n            if (!node.children.has(ch)) {\n                return -1;\n            }\n            const nodeValue = node.children.get(ch);\n            if (nodeValue === undefined) throw new Error(\"KeyError\");\n            node = nodeValue;\n        }\n        return node.index;\n    }\n}","lineMap":{"3":6,"4":7,"8":15,"9":16,"10":18,"11":19,"12":20,"13":21,"14":22,"15":23,"16":24,"17":25,"18":27,"19":28,"20":29,"23":37,"24":38,"25":39,"26":40,"27":41,"28":42,"29":44,"30":48},"statementBundles":{"4":{"startLine":7,"endLine":14},"9":{"startLine":16,"endLine":17},"17":{"startLine":25,"endLine":26},"20":{"startLine":29,"endLine":36},"28":{"startLine":42,"endLine":43},"29":{"startLine":44,"endLine":47},"30":{"startLine":48,"endLine":50}}}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"class TrieNode {\n    Map<String, TrieNode> children;\n    int index;\n\n    public TrieNode() {\n        this.children = new HashMap<String, TrieNode>();\n        this.index = -1;\n    }\n}\nclass WordFilter {\n    TrieNode root;\n\n    public WordFilter(List<String> words) {\n        this.root = new TrieNode();\n        for (int idx = 0; idx < words.size(); idx++) {\n            String word = words.get(idx);\n            int size = word.length();\n            for (int i = 0; i < (size + 1); i++) {\n                String key = (word.substring(i, word.length()) + \"#\") + word;\n                TrieNode node = this.root;\n                for (int position = 0; position < key.length(); position++) {\n                    String ch = String.valueOf(key.charAt(position));\n                    if (!node.children.containsKey(ch)) {\n                        node.children.put(ch, new TrieNode());\n                    }\n                    node = node.children.get(ch);\n                    if (node.index == -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    public int f(String prefix, String suffix) {\n        String key = (suffix + \"#\") + prefix;\n        TrieNode node = this.root;\n        for (int position = 0; position < key.length(); position++) {\n            String ch = String.valueOf(key.charAt(position));\n            if (!node.children.containsKey(ch)) {\n                return -1;\n            }\n            node = node.children.get(ch);\n        }\n        return node.index;\n    }\n}","lineMap":{"3":6,"4":7,"8":14,"9":15,"10":17,"11":18,"12":19,"13":20,"14":21,"15":22,"16":23,"17":24,"18":26,"19":27,"20":28,"23":36,"24":37,"25":38,"26":39,"27":40,"28":41,"29":43,"30":45},"statementBundles":{"4":{"startLine":7,"endLine":13},"9":{"startLine":15,"endLine":16},"17":{"startLine":24,"endLine":25},"20":{"startLine":28,"endLine":35},"28":{"startLine":41,"endLine":42},"29":{"startLine":43,"endLine":44},"30":{"startLine":45,"endLine":47}},"alternateStyles":{"close-to-source":{"code":"class TrieNode {\n\n\n    Map<String, TrieNode> children;\n    int index;\n\n    public TrieNode() {\n        this.children = new HashMap<String, TrieNode>();\n        this.index = -1;\n    }\n}\nclass WordFilter {\n    static <K, V> V requireMapValue(Map<K, V> values, K key) { if (!values.containsKey(key)) throw new NoSuchElementException(\"KeyError\"); return values.get(key); }\n\n    TrieNode root;\n\n    public WordFilter(List<String> words) {\n        this.root = new TrieNode();\n        for (int idx = 0; idx < words.size(); idx++) {\n            String word = words.get(idx);\n            int size = word.length();\n            for (int i = 0; i < (size + 1); i++) {\n                String key = (word.substring(i, word.length()) + \"#\") + word;\n                TrieNode node = this.root;\n                for (int position = 0; position < key.length(); position++) {\n                    String ch = String.valueOf(key.charAt(position));\n                    if (!node.children.containsKey(ch)) {\n                        node.children.put(ch, new TrieNode());\n                    }\n                    node = node.children.get(ch);\n                    if (node.index == -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    public int f(String prefix, String suffix) {\n        String key = (suffix + \"#\") + prefix;\n        TrieNode node = this.root;\n        for (int position = 0; position < key.length(); position++) {\n            String ch = String.valueOf(key.charAt(position));\n            if (!node.children.containsKey(ch)) {\n                return -1;\n            }\n            node = requireMapValue(node.children, ch);\n        }\n        return node.index;\n    }\n}","lineMap":{"3":8,"4":9,"8":18,"9":19,"10":21,"11":22,"12":23,"13":24,"14":25,"15":26,"16":27,"17":28,"18":30,"19":31,"20":32,"23":40,"24":41,"25":42,"26":43,"27":44,"28":45,"29":47,"30":49},"statementBundles":{"4":{"startLine":9,"endLine":17},"9":{"startLine":19,"endLine":20},"17":{"startLine":28,"endLine":29},"20":{"startLine":32,"endLine":39},"28":{"startLine":45,"endLine":46},"29":{"startLine":47,"endLine":48},"30":{"startLine":49,"endLine":51}}}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"public class TrieNode\n{\n    public Dictionary<string, TrieNode> children;\n    public int index;\n\n    public TrieNode()\n    {\n        this.children = new Dictionary<string, TrieNode>();\n        this.index = -1;\n    }\n}\n\npublic class WordFilter\n{\n    public TrieNode root;\n\n    public WordFilter(List<string> words)\n    {\n        this.root = new TrieNode();\n        for (int idx = 0; idx < words.Count; idx++) {\n            string word = words[idx];\n            int size = word.Length;\n            for (int i = 0; i < size + 1; i++) {\n                string key1 = word.Substring(i, (word.Length) - (i)) + \"#\" + word;\n                TrieNode node = this.root;\n                for (int position = 0; position < key1.Length; position++) {\n                    string ch1 = key1[position].ToString();\n                    if (!node.children.ContainsKey(ch1)) {\n                        node.children[ch1] = new TrieNode();\n                    }\n                    node = node.children[ch1];\n                    if (node.index == -1) {\n                        node.index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    public int F(string prefix, string suffix)\n    {\n        string key = suffix + \"#\" + prefix;\n        TrieNode node = this.root;\n        for (int position = 0; position < key.Length; position++) {\n            string ch = key[position].ToString();\n            if (!node.children.ContainsKey(ch)) {\n                return -1;\n            }\n            node = node.children[ch];\n        }\n        return node.index;\n        return 0;\n    }\n}","lineMap":{"3":8,"4":9,"8":19,"9":20,"10":22,"11":23,"12":24,"13":25,"14":26,"15":27,"16":28,"17":29,"18":31,"19":32,"20":33,"23":42,"24":43,"25":44,"26":45,"27":46,"28":47,"29":49,"30":51},"statementBundles":{"4":{"startLine":9,"endLine":18},"9":{"startLine":20,"endLine":21},"17":{"startLine":29,"endLine":30},"20":{"startLine":33,"endLine":41},"28":{"startLine":47,"endLine":48},"29":{"startLine":49,"endLine":50},"30":{"startLine":51,"endLine":54}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"struct TrieNode;\nstruct WordFilter;\n\nstruct TrieNode {\n    unordered_map<string, TrieNode*> children;\n    int index;\n\n    TrieNode() {\n        this->children = unordered_map<string, TrieNode*>{};\n        this->index = -1;\n    }\n};\n\nstruct WordFilter {\n    TrieNode* root;\n\n    WordFilter(vector<string> words) {\n        this->root = new TrieNode();\n        for (int idx = 0; idx < words.size(); idx++) {\n            string word = words[idx];\n            int size = word.size();\n            for (int i = 0; i < (size + 1); i++) {\n                string key = (string(word.begin() + i, word.begin() + word.size()) + \"#\") + word;\n                TrieNode* node = this->root;\n                for (int position = 0; position < key.size(); position++) {\n                    string ch = string(1, key[position]);\n                    if (!node->children.count(ch)) {\n                        node->children[ch] = new TrieNode();\n                    }\n                    node = node->children.at(ch);\n                    if (node->index == -1) {\n                        node->index = idx;\n                    }\n                }\n            }\n        }\n    }\n\n    int f(string prefix, string suffix) {\n        string key = (suffix + \"#\") + prefix;\n        TrieNode* node = this->root;\n        for (int position = 0; position < key.size(); position++) {\n            string ch = string(1, key[position]);\n            if (!node->children.count(ch)) {\n                return -1;\n            }\n            node = node->children.at(ch);\n        }\n        return node->index;\n    }\n};","lineMap":{"3":9,"4":10,"8":18,"9":19,"10":21,"11":22,"12":23,"13":24,"14":25,"15":26,"16":27,"17":28,"18":30,"19":31,"20":32,"23":40,"24":41,"25":42,"26":43,"27":44,"28":45,"29":47,"30":49},"statementBundles":{"4":{"startLine":10,"endLine":17},"9":{"startLine":19,"endLine":20},"17":{"startLine":28,"endLine":29},"20":{"startLine":32,"endLine":39},"28":{"startLine":45,"endLine":46},"29":{"startLine":47,"endLine":48},"30":{"startLine":49,"endLine":51}}}}}},{"id":"edge-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Which inputs could break this?","summary":"A composite-key trie is only as good as the keys it builds and the index it keeps on each node.","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"}],"edges":[["e","e#"],["e#","e#a"]],"current":"e#a","highlighted":["e","e#","e#a"]}}}]},"body":["Three pressures sit at the edges. An empty prefix or suffix names the empty string, which the separator-based key has to represent without a special branch. A query for a pair no word has must stop cleanly and return -1. And when duplicate or overlapping words match the same query, the largest index must win.","If the keys are built as suffix + '#' + word for every suffix and the index is overwritten on every visited node, each of these should fall out of the same code with no extra case."]},{"id":"edge-zero","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"What does an empty prefix or suffix do to the key?","summary":"f(\"\", \"e\") asks for any word ending in \"e\", with no constraint on the start.","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-side","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"}],"edges":[["e","e#"]],"current":"e#","highlighted":["e","e#"],"activeEdges":[["e","e#"]]}}}]},"options":[{"id":"same-shape","label":"Nothing special: the key is just suffix + '#' + prefix with an empty part","rationale":"With prefix empty, suffix + '#' + prefix is \"e\" + \"#\" + \"\" = \"e#\", so the walk stops right after the separator. Every word's keys pass through that \"e#\" node, and it carries the latest matching index, so f(\"\", \"e\") returns the largest word ending in \"e\" with no extra branch.","isCorrect":true},{"id":"needs-guard","label":"It needs a separate branch that returns the global largest index","rationale":"No special branch is required. The separator-based key already represents the empty side: walking up to the \"#\" node lands on the node every suffix path shares, which holds the right answer.","isCorrect":false},{"id":"returns-neg1","label":"It returns -1, because an empty string is not a real prefix","rationale":"An empty prefix matches every word, so it should not fail. The key e# exists as long as any word ends in \"e\", and the node there stores the largest such index.","isCorrect":false}],"answer":"Nothing special happens. An empty side just makes that part of the key empty, so f(\"\", \"e\") walks e# and reads the largest index of any word ending in \"e\". The separator is what lets the empty case share the same path-walking code."},{"id":"edge-overflow","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Two words match a query: which index is returned?","summary":"words = [\"apple\", \"ape\"], and both satisfy f(\"ap\", \"e\").","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"overlap","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#apple","label":"..ple"},{"id":"e#ape","label":"..e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#apple"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e#ap"]}}}]},"options":[{"id":"largest","label":"The largest index, because later words overwrote the node","rationale":"Both words stamp the shared e#ap node during insertion, but \"ape\" comes later in index order, so its index 2 overwrites \"apple\"'s 0. The query reads 2, the largest matching index, with no comparison at query time.","isCorrect":true},{"id":"first","label":"The first matching index, since it was written first","rationale":"Returning the first index would give 0, but the problem wants the largest. Because insertion always overwrites with the current index and words arrive in increasing order, the node already holds the largest match.","isCorrect":false},{"id":"both","label":"Both, so the caller must pick the larger","rationale":"A trie node stores a single index. The overwrite during insertion collapses all matches at that node down to the largest one, so f returns a single number directly.","isCorrect":false}],"answer":"The largest index, 2. Inserting words in order and overwriting node.index each time means the shared node ends up holding the latest, and therefore largest, matching index. Duplicates behave the same way: a repeated word's later index simply overwrites the earlier one."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the design into code","summary":"Two pieces: build composite keys in the constructor, walk one key per query.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready","state":{"graph":{"nodes":[{"id":"e","label":"e"},{"id":"e#","label":"#"},{"id":"e#a","label":"a"},{"id":"e#ap","label":"p"},{"id":"e#ape","label":"e"}],"edges":[["e","e#"],["e#","e#a"],["e#a","e#ap"],["e#ap","e#ape"]],"current":"e#ap","highlighted":["e","e#","e#a","e#ap"]}}}]},"body":["In __init__, allocate one root node. For each word at its index, take every suffix, form key = suffix + '#' + word, and walk that key into the trie, creating missing children and writing the current index onto every node you pass. Because words are processed in order, later writes keep the largest matching index.","In f, build key = suffix + '#' + prefix and walk it from the root. If a character is missing, no word has both ends, so return -1. Otherwise return the index stored on the node you reach."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build WordFilter lookups","summary":"Create the root, build each suffix key, insert composite paths, stamp the current index along the path, walk the query key, and return the stored index or -1.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Preprocess once into a composite-key trie, then answer each query by walking a single path.","workspacePanel":"code","body":["There is no per-query scanning here. The constructor spends O(m squared) per word building keys of the form suffix + '#' + word, so every possible suffix becomes a reachable path. After that, each f only reads its own prefix and suffix characters, trading memory for fast repeated lookups.","Correctness rests on two moves: the separator joins the two conditions into one path, and overwriting node.index on every visit keeps the largest matching index, since words are inserted in increasing order."],"takeaways":[{"title":"Preprocessing trades memory for fast queries","body":"Building every suffix + '#' + word key costs O(m squared) per word and O(n m squared) space, but then each f runs in O(prefix + suffix) instead of re-scanning all n words on every call."},{"title":"suffix + '#' + prefix turns two conditions into one path","body":"Gluing the suffix and the word with a separator lets a query walk the ending then the beginning down a single trie path, so one traversal settles both the prefix and the suffix without intersecting two searches."},{"title":"Overwriting node.index keeps the largest match","body":"Words are inserted in index order and each visit overwrites the stored index, so a shared node ends up holding the latest, and therefore largest, matching index; a completed walk returns it, a missing character returns -1."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"complexity":{"time":"Constructor: O(n * m^2), f: O(prefix.length + suffix.length)","space":"O(n * m^2)"}}
