In-Memory Exact Suffix Query Index
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Build an in-memory string index that supports interleaved string insertions and exact, case-sensitive suffix queries.
Design a SuffixIndex class with the following methods:
SuffixIndex()— creates an empty index.insert(word: str) -> None— addswordto the index.has_suffix(suffix: str) -> bool— returnsTrueif at least one previously inserted string ends withsuffix(matching character-for-character, including letter case), andFalseotherwise.
To evaluate sequences of interleaved calls, implement run_suffix_index(operations, arguments), where operations[i] is either "insert" or "has_suffix" and arguments[i] is a one-element list [text] holding the string argument for that call. Replay all calls in order against a single SuffixIndex instance and return a list of results containing None for each "insert" and True or False for each "has_suffix".
Notes on boundary behavior:
- Every string counts as a suffix of itself (after
insert("packet"),has_suffix("packet")returnsTrue). - Calling
has_suffixbefore any string has been inserted returnsFalse. - Duplicate insertions of the same string are allowed.
Examples
Example 1
Input:
- operations = ['insert', 'insert', 'insert', 'has_suffix', 'has_suffix', 'has_suffix', 'has_suffix', 'has_suffix']
- arguments = [['notebook'], ['handbook'], ['textbook'], ['book'], ['ebook'], ['note'], ['k'], ['shelf']]
Output: [None, None, None, True, True, False, True, False]
Explanation: After inserting "notebook", "handbook", and "textbook", "book" and "k" match the endings of all three strings, and "ebook" matches "notebook". "note" is a prefix rather than an ending (False), and "shelf" matches none of the inserted strings (False).
Example 2
Input:
- operations = ['has_suffix', 'insert', 'has_suffix', 'insert', 'has_suffix', 'has_suffix']
- arguments = [['z'], ['z'], ['z'], ['Metric'], ['metric'], ['tric']]
Output: [False, None, True, None, False, True]
Explanation: The initial query for "z" runs on an empty index (False), then succeeds once "z" is inserted (True). After inserting "Metric", "metric" fails because 'M' and 'm' differ in case (False), whereas "tric" matches the last four characters (True).
Example 3
Input:
- operations = ['insert', 'insert', 'has_suffix', 'has_suffix', 'has_suffix']
- arguments = [['packet'], ['socket'], ['packet'], ['cket'], ['datapacket']]
Output: [None, None, True, True, False]
Explanation: "packet" matches itself in full (True), "cket" matches both "packet" and "socket" (True), and "datapacket" is longer than every stored string (False).
Constraints
1 <= len(word), len(suffix) <= 2,000wordandsuffixconsist of printable ASCII characters and comparisons are case-sensitive.1 <= len(operations) == len(arguments) <= 100,000- The sum of
len(word)across all"insert"calls is at most1,000,000.
Step-by-step walkthrough
Understand the operations and constraints
We need an in-memory index
SuffixIndexthat supports two interleaved operations on case-sensitive printable ASCII strings:insert(word)addswordto the collection (returns nothing;run_suffix_indexrecordsNone).has_suffix(suffix)returnsTrueif at least one word inserted so far ends withsuffix, orFalseotherwise. A full word counts as a suffix of itself ("packet"ends with"packet").
Look closely at the scale limits:
- Up to
100,000combined calls toinsertandhas_suffix. - Each
wordorsuffixhas length1 .. 2,000. - The sum of lengths of all inserted words is at most
1,000,000characters.
Brute force and why scanning every word is too slow
Two obvious first attempts hit a wall on these limits:
- Scan all stored words per query (
word.endswith(suffix)): with50,000stored words and50,000queries, queries perform up to50,000 * 50,000 = 2.5 * 10^9string checks—far too slow when many queries miss. - Insert every suffix slice into a
set: slicingword[i:]for everyicopies1 + 2 + ... + L = L * (L + 1) / 2characters per word. A single2,000-character word generates~2,000,000characters of slices, blowing past memory limits when500long words are inserted.
We want each
insert(word)to touch onlylen(word)characters and eachhas_suffix(suffix)to touch onlylen(suffix)characters, independent of how many words are stored.- Scan all stored words per query (
Key insight: a reversed trie with no end-of-word flag
A trie (prefix tree) is a tree where each edge is labeled with a single character, so strings that start with the same letters share one path from the root.
Reading strings from right to left turns every suffix check into a prefix check:
word ends with suffix <=> reversed(word) starts with reversed(suffix)If we insert
"notebook","handbook", and"textbook"backwards into a trie, their shared"book"ending collapses onto one shared pathroot -> 'k' -> 'o' -> 'o' -> 'b':root └── 'k' └── 'o' └── 'o' └── 'b' <-- has_suffix("book") stops right here and returns True! ├── 'e' -> 't' -> 'o' -> 'n' ("notebook") ├── 'd' -> 'n' -> 'a' -> 'h' ("handbook") └── 't' -> 'x' -> 'e' -> 't' ("textbook")Notice a simplifying twist compared to a standard dictionary trie: we do not need an
is_end_of_wordboolean on nodes. Every node in the tree was created by walking backwards from the end of some inserted word, so reaching any node after consumingreversed(suffix)proves that at least one inserted word ends withsuffix.Code the SuffixIndex class
Represent each trie node as a plain Python dictionary mapping a character
chto its child dictionary:- Printable ASCII spans
95characters (uppercase, lowercase, digits, spaces, symbols), so a dictionary allocates entries only for characters that actually appear instead of wasting a95-element array at every node. - Python's built-in
reversed(text)iterates from the last character to the first inO(1)extra memory without allocating a reversed copy of the string.
class SuffixIndex: def __init__(self) -> None: # root: nested dict representing a trie of REVERSED words. # Mini-shape after insert("cat"): {'t': {'a': {'c': {}}}} self.root: Dict[str, Any] = {} def insert(self, word: str) -> None: # Phase 1: Walk `word` from last character to first, creating missing child dicts. # No end-of-word flag is needed because every prefix of a reversed word # is already a valid suffix of the original word. node = self.root for ch in reversed(word): if ch not in node: node[ch] = {} node = node[ch] def has_suffix(self, suffix: str) -> bool: # Guard: if no words have been inserted yet, no word can match any suffix. if not self.root: return False # Phase 2: Walk `suffix` from last character to first along the reversed trie. node = self.root for ch in reversed(suffix): if ch not in node: return False node = node[ch] # Consuming every character proves at least one inserted word ends with `suffix`. return True- Printable ASCII spans
Code the judge driver function
The automated judge passes parallel lists
operationsandarguments. We instantiate a singleSuffixIndex, replay each call in sequence so queries only see earlier inserts, and collectNonefor"insert"or the boolean answer for"has_suffix".def run_suffix_index(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]: # Replay interleaved insert and has_suffix operations in order against one SuffixIndex. index = SuffixIndex() results: List[Optional[bool]] = [] for op, args in zip(operations, arguments): if op == "insert": index.insert(args[0]) results.append(None) elif op == "has_suffix": results.append(index.has_suffix(args[0])) else: raise ValueError(f"Unknown operation: {op}") return resultsTrace Example 1 through the reversed trie
After inserting
"notebook","handbook", and"textbook", let's trace each query in Example 1:1. has_suffix("book") -> walk 'k' -> 'o' -> 'o' -> 'b': all found => True 2. has_suffix("ebook") -> walk 'k' -> 'o' -> 'o' -> 'b' -> 'e': all found => True 3. has_suffix("note") -> first reversed char is 'e'; root only has 'k' => False (1 step!) 4. has_suffix("k") -> walk 'k': found under root => True 5. has_suffix("shelf") -> first reversed char is 'f'; root only has 'k' => False (1 step!)Notice how
"note"(a prefix, not a suffix) and"shelf"fail on their very first character instead of scanning through any stored words.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class SuffixIndex: def __init__(self) -> None: # root: nested dict representing a trie of REVERSED words. # Mini-shape after insert("cat"): {'t': {'a': {'c': {}}}} self.root: Dict[str, Any] = {} def insert(self, word: str) -> None: # Phase 1: Walk `word` from last character to first, creating missing child dicts. # No end-of-word flag is needed because every prefix of a reversed word # is already a valid suffix of the original word. node = self.root for ch in reversed(word): if ch not in node: node[ch] = {} node = node[ch] def has_suffix(self, suffix: str) -> bool: # Guard: if no words have been inserted yet, no word can match any suffix. if not self.root: return False # Phase 2: Walk `suffix` from last character to first along the reversed trie. node = self.root for ch in reversed(suffix): if ch not in node: return False node = node[ch] # Consuming every character proves at least one inserted word ends with `suffix`. return True def run_suffix_index(operations: List[str], arguments: List[List[str]]) -> List[Optional[bool]]: # Replay interleaved insert and has_suffix operations in order against one SuffixIndex. index = SuffixIndex() results: List[Optional[bool]] = [] for op, args in zip(operations, arguments): if op == "insert": index.insert(args[0]) results.append(None) elif op == "has_suffix": results.append(index.has_suffix(args[0])) else: raise ValueError(f"Unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine filing words in a nested folder cabinet by reading every word from its last letter back to its first: words that share an ending—like "notebook" and "handbook"—walk down the exact same folder path 'k' -> 'o' -> 'o' -> 'b' before branching off into their own sub-folders.
Keeping words in a plain list and checking word.endswith(suffix) re-scans every stored word on every query, which grinds to a halt when tens of thousands of queries meet tens of thousands of words. Alternatively, slicing all L suffixes of a word into a hash set makes queries fast, but a single 2,000-character word creates roughly 2,000,000 characters of substring copies. Storing reversed words inside a trie (a tree where each edge represents one character so shared beginnings share a single path from the root) stores each inserted character at most once and answers any suffix lookup in O(len(suffix)) steps regardless of how many words are in the index.
Walk through Example 3 with "packet" and "socket":
1. insert("packet") walks backwards (t -> e -> k -> c -> a -> p) from self.root, creating nested dictionaries along that chain.
2. insert("socket") walks backwards (t -> e -> k -> c -> o -> s), reusing the existing 't' -> 'e' -> 'k' -> 'c' dictionaries and branching off at 'o'.
3. has_suffix("cket") walks 't' -> 'e' -> 'k' -> 'c', finds all four keys, and returns True without needing an end-of-word marker; has_suffix("datapacket") runs out of children after 'p' and returns False.
Complexity
Let L be the length of the word or suffix passed to a single call, and S be the sum of lengths of all inserted words (S <= 1,000,000).
- Time:
O(L)average time perinsert(word)andO(L)average time perhas_suffix(suffix), because we iterate through theLcharacters once in reverse and perform oneO(1)average-time dictionary lookup (and optional insertion) at each character. Query speed depends only onlen(suffix), never on the number of stored words. - Space:
O(S)total space across the entire life of the index, because each character of an inserted word creates at most one new dictionary entry (and characters in shared suffixes reuse existing nodes), plusO(1)extra working space duringreversed(...)iteration.
Edge cases
- Querying an empty index:
self.rootis empty ({}), sohas_suffiximmediately returnsFalse. - Whole word queried as its own suffix:
insert("packet")followed byhas_suffix("packet")traverses all6edges and returnsTrue. - Suffix longer than any stored word:
insert("packet")followed byhas_suffix("datapacket")runs out of child keys after't' -> 'e' -> 'k' -> 'c' -> 'a' -> 'p'and returnsFalse. - Prefix or middle substring:
"note"or"tebo"fails as soon as its reversed characters diverge from actual word endings. - Case sensitivity and punctuation:
"Metric"stores'M'at the deepest edge while"metric"looks for'm', returningFalse; spaces and symbols work identically to letters because dictionary keys hold any character. - Duplicate
insertcalls: inserting"abc"twice simply walks the existing'c' -> 'b' -> 'a'path without adding nodes or changing query answers.
Common mistakes
- Traversing left-to-right instead of right-to-left: building a forward trie tests prefixes (
startswith), not suffixes (endswith). Bothinsertandhas_suffixmust iterate in reverse. - Requiring an
is_endmarker onhas_suffix: unlike exact dictionary lookup, stopping partway down a reversed word's path still matches a true suffix of that longer word. - Allocating a fixed
26-element array per node: assuming'a'..'z'crashes on uppercase letters, digits, spaces, and punctuation allowed by printable ASCII. - Slicing
word[::-1]when memory is tight on huge strings:reversed(word)yields characters lazily inO(1)space without allocating a copy.
Alternative approaches
- Sorted array of reversed words + binary search: reversing every word and keeping them sorted turns
has_suffix(s)into checking whether the first entry>= s[::-1]starts withs[::-1]inO(L log N)time, but inserting into a dynamic Python list shiftsO(N)pointers per insert (unless backed by a balanced search tree). - Rolling polynomial hash (Rabin-Karp) of suffixes: storing 64-bit hashes of every suffix of every inserted word takes
O(S)integers in a hash set andO(L)per query, though hash collisions require either double hashing or storing(word_id, offset)verification pointers.
Follow-up questions
- How would you modify the structure so a query returns the count of inserted strings that share the given suffix? Store an integer
pass_counton every trie node and incrementpass_counton each node visited duringinsert(word). Becausepass_countrecords how many reversed words pass through that node,count_suffix(suffix)simply walksreversed(suffix)and returns the final node'spass_count(or0if any character is missing) inO(L)time. If duplicate insertions of the same word should only count once, keep aseen_wordshash set (or check anend_counton the terminal node first) and skipinsertwhen the word is already present. - How could you add a
remove(word)method that also reclaims unused nodes so memory does not grow unboundedly? Track bothpass_count(words passing through a node) andend_count(words ending at that exact node) on every node. To removeword, first walkreversed(word)to confirm the final node hasend_count > 0(soremove("ook")cannot corrupt"notebook"when"ook"itself was never inserted); then walkreversed(word)a second time, decrementing each child'spass_count, and the moment a child'spass_counthits0, deletedel parent.children[ch]and stop—instantly freeing that node and any orphan nodes (unreachable descendant nodes no longer used by any remaining word). If no child dropped to0, decrementend_counton the final node so longer words sharing the path remain intact. - When storing millions of lengthy strings that share long common endings, how would you collapse single-child paths to reduce pointer overhead? Replace every chain of single-child nodes with a single edge labeled by a multi-character substring, forming a radix tree (Patricia trie) (a space-optimized trie that merges non-branching character chains into single string-labeled edges). To avoid duplicating string data, represent each edge label as
(word_id, start, end)pointing into a compact buffer of reversed words. Duringinsert, walk matching characters along each edge label and split an edge into two only where a new word diverges; duringhas_suffix, returnTrueeven if the reversed suffix finishes partway through an edge label, reducing total node count fromO(S)characters down toO(W)forWdistinct words while keepingO(L)query time.
Follow-up questions
- How would you modify the structure so a query returns the count of inserted strings that share the given suffix?
- How could you add a `remove(word)` method that also reclaims unused nodes so memory does not grow unboundedly?
- When storing millions of lengthy strings that share long common endings, how would you collapse single-child paths to reduce pointer overhead?
Similar questions
- Variadic Prefix Expression Evaluator
- Identify Unreferenced Heap Allocations From Stack Roots
- Identify Unreachable Heap Allocations
- Optimal Revenue From Rod Cutting
- Debugging Browser Memory Leaks in a Long-Running Web Console
- Hash Table Collision Strategies and Performance
More Anduril interview questions
- Debugging Browser Memory Leaks in a Long-Running Web Console Medium
- Variadic Prefix Expression Evaluator Medium
- Hash Table Collision Strategies and Performance Medium Pro
- Identify Unreferenced Heap Allocations From Stack Roots Medium Pro
- Identify Unreachable Heap Allocations Medium Pro
- Optimal Revenue From Rod Cutting Medium Pro