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 — adds word to the index.
  • has_suffix(suffix: str) -> bool — returns True if at least one previously inserted string ends with suffix (matching character-for-character, including letter case), and False otherwise.

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") returns True).
  • Calling has_suffix before any string has been inserted returns False.
  • 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,000
  • word and suffix consist 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 most 1,000,000.

Step-by-step walkthrough

  1. Understand the operations and constraints

    We need an in-memory index SuffixIndex that supports two interleaved operations on case-sensitive printable ASCII strings:

    • insert(word) adds word to the collection (returns nothing; run_suffix_index records None).
    • has_suffix(suffix) returns True if at least one word inserted so far ends with suffix, or False otherwise. A full word counts as a suffix of itself ("packet" ends with "packet").

    Look closely at the scale limits:

    • Up to 100,000 combined calls to insert and has_suffix.
    • Each word or suffix has length 1 .. 2,000.
    • The sum of lengths of all inserted words is at most 1,000,000 characters.
  2. Brute force and why scanning every word is too slow

    Two obvious first attempts hit a wall on these limits:

    1. Scan all stored words per query (word.endswith(suffix)): with 50,000 stored words and 50,000 queries, queries perform up to 50,000 * 50,000 = 2.5 * 10^9 string checks—far too slow when many queries miss.
    2. Insert every suffix slice into a set: slicing word[i:] for every i copies 1 + 2 + ... + L = L * (L + 1) / 2 characters per word. A single 2,000-character word generates ~2,000,000 characters of slices, blowing past memory limits when 500 long words are inserted.

    We want each insert(word) to touch only len(word) characters and each has_suffix(suffix) to touch only len(suffix) characters, independent of how many words are stored.

  3. 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 path root -> '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_word boolean on nodes. Every node in the tree was created by walking backwards from the end of some inserted word, so reaching any node after consuming reversed(suffix) proves that at least one inserted word ends with suffix.

  4. Code the SuffixIndex class

    Represent each trie node as a plain Python dictionary mapping a character ch to its child dictionary:

    • Printable ASCII spans 95 characters (uppercase, lowercase, digits, spaces, symbols), so a dictionary allocates entries only for characters that actually appear instead of wasting a 95-element array at every node.
    • Python's built-in reversed(text) iterates from the last character to the first in O(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
    
  5. Code the judge driver function

    The automated judge passes parallel lists operations and arguments. We instantiate a single SuffixIndex, replay each call in sequence so queries only see earlier inserts, and collect None for "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 results
    
  6. Trace 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.

  7. 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 per insert(word) and O(L) average time per has_suffix(suffix), because we iterate through the L characters once in reverse and perform one O(1) average-time dictionary lookup (and optional insertion) at each character. Query speed depends only on len(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), plus O(1) extra working space during reversed(...) iteration.

Edge cases

  • Querying an empty index: self.root is empty ({}), so has_suffix immediately returns False.
  • Whole word queried as its own suffix: insert("packet") followed by has_suffix("packet") traverses all 6 edges and returns True.
  • Suffix longer than any stored word: insert("packet") followed by has_suffix("datapacket") runs out of child keys after 't' -> 'e' -> 'k' -> 'c' -> 'a' -> 'p' and returns False.
  • 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', returning False; spaces and symbols work identically to letters because dictionary keys hold any character.
  • Duplicate insert calls: 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). Both insert and has_suffix must iterate in reverse.
  • Requiring an is_end marker on has_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 in O(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 with s[::-1] in O(L log N) time, but inserting into a dynamic Python list shifts O(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 and O(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_count on every trie node and increment pass_count on each node visited during insert(word). Because pass_count records how many reversed words pass through that node, count_suffix(suffix) simply walks reversed(suffix) and returns the final node's pass_count (or 0 if any character is missing) in O(L) time. If duplicate insertions of the same word should only count once, keep a seen_words hash set (or check an end_count on the terminal node first) and skip insert when 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 both pass_count (words passing through a node) and end_count (words ending at that exact node) on every node. To remove word, first walk reversed(word) to confirm the final node has end_count > 0 (so remove("ook") cannot corrupt "notebook" when "ook" itself was never inserted); then walk reversed(word) a second time, decrementing each child's pass_count, and the moment a child's pass_count hits 0, delete del 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 to 0, decrement end_count on 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. During insert, walk matching characters along each edge label and split an edge into two only where a new word diverges; during has_suffix, return True even if the reversed suffix finishes partway through an edge label, reducing total node count from O(S) characters down to O(W) for W distinct words while keeping O(L) query time.

Follow-up questions

Similar questions

More Anduril interview questions

All 7 Anduril questions →