Ranked Prefix Autocomplete With Request Ordering

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build an in-memory autocomplete backend that indexes weighted catalog titles, returns ranked prefix suggestions on each keystroke, and drops out-of-order responses from earlier asynchronous requests.

Implement a PrefixSearchEngine class along with the batch runner function below:

def prefix_search_engine(
    titles: List[Tuple[str, int]],
    operations: List[str],
    arguments: List[List[object]],
) -> List[Optional[List[str]]]:

Class & Runner Specification

  1. PrefixSearchEngine(titles: List[Tuple[str, int]]):
    • Loads (title, popularity) entries where title is a non-empty string and popularity is a positive integer score.
    • If the exact same title string (case-sensitive) appears more than once, deduplicate it by keeping only its maximum popularity score. Titles that differ in letter casing (such as "Guide" and "guide") remain distinct entries.
  2. query(prefix: str, request_id: int, limit: int = 5) -> Optional[List[str]]:
    • Out-of-order filtering: Track the largest request_id accepted so far (starting from 0). Whenever request_id is less than or equal to that highest processed ID, treat the call as stale: leave the watermark unchanged and return None.
    • Prefix matching: Match every unique title whose full text begins with prefix ignoring letter case (title.lower().startswith(prefix.lower())), while returning each matched title in its original casing.
    • Ranking & truncation: Order matches by popularity descending first, breaking ties by standard ascending string order (< on the original-cased title), and return at most limit titles. If a non-stale query matches zero titles, update the watermark and return [].
  3. prefix_search_engine(titles, operations, arguments):
    • Instantiates PrefixSearchEngine(titles) once and runs each "query" operation using arguments[i] ([prefix, request_id] or [prefix, request_id, limit]), returning the list of outputs in call order.

Examples

Example 1

  • Input: python titles = [ ("Deploy Pipeline Guide", 85), ("deploy preview service", 140), ("Database Failover Runbook", 210), ("Deploy Canary Checklist", 85), ("Docker Base Images", 60), ] operations = ["query", "query", "query"] arguments = [["dep", 2, 3], ["d", 5, 2], ["deploy", 4, 5]]
  • Output: python [ ["deploy preview service", "Deploy Canary Checklist", "Deploy Pipeline Guide"], ["Database Failover Runbook", "deploy preview service"], None, ]
  • Explanation:
    • Call 1 (request_id = 2): Fresh (2 > 0). Three titles begin with "dep" case-insensitively; score 140 ranks first, and the tie at 85 orders "Deploy Canary Checklist" ahead of "Deploy Pipeline Guide".
    • Call 2 (request_id = 5): Fresh (5 > 2). All five titles begin with "d", and limit = 2 keeps scores 210 and 140.
    • Call 3 (request_id = 4): Stale (4 <= 5), so None is returned immediately.

Example 2

  • Input: python titles = [ ("Metrics Overview", 40), ("Metrics Overview", 90), ("metrics alerts", 75), ("Mesh Routing", 90), ] operations = ["query", "query", "query"] arguments = [["me", 1], ["zzz", 3, 4], ["me", 2, 2]]
  • Output: python [ ["Mesh Routing", "Metrics Overview", "metrics alerts"], [], None, ]
  • Explanation: Exact duplicate "Metrics Overview" keeps score 90 and ties with "Mesh Routing" ("Mesh Routing" < "Metrics Overview"). Call 1 uses the default limit = 5; Call 2 matches nothing ([]) while advancing the watermark to 3; Call 3 (2 <= 3) is rejected as stale (None).

Constraints

  • At most 50,000 unique titles, with average length at most 80 characters
  • 0 <= len(prefix) <= 50
  • 1 <= request_id <= 10^9
  • 1 <= limit <= 50 (defaults to 5 when omitted)

Step-by-step walkthrough

  1. Understand the search rules and stale-request contract

    In a search-as-you-type box, every keystroke fires an asynchronous request (request_id = 1, 2, 3, ...). Because network latency varies, response 2 can arrive after response 3 has already been processed; showing response 2 would overwrite newer results with stale ones.

    Our PrefixSearchEngine loads (title, popularity) pairs once and answers query(prefix, request_id, limit=5) under five rules:

    1. Stale protection: track the highest request_id processed so far (max_request_id, initialized to 0). If request_id <= max_request_id, return None immediately and leave max_request_id unchanged.
    2. Case-insensitive prefix match, original-case output: "dep" matches "Deploy Pipeline Guide", and the returned list keeps "Deploy Pipeline Guide" with its original capital letters.
    3. Deduplication: if the exact same title string appears multiple times in titles, keep only its highest popularity score ("Notes" and "notes" differ in casing, so they remain distinct titles).
    4. Ranking: sort matches by descending popularity first, breaking ties by ascending lexicographical order (< on the original title string, where ASCII uppercase letters come before lowercase, e.g., "Apricot" < "apple").
    5. Empty matches vs. stale queries: a valid query with no matching titles returns [] (never None, which means stale) and still updates max_request_id.
  2. Why scanning on every keystroke is too slow — and how a cached trie fixes it

    A naive implementation scans all N titles on every keystroke, checks title.lower().startswith(prefix.lower()), and sorts all matches. With N = 50,000 titles and queries firing on every keystroke, scanning and sorting tens of thousands of strings per character typed wastes CPU.

    A trie (prefix tree) is a tree where each edge is labeled with one lowercase character, so walking down 'a' -> 'l' -> 'p' lands on a single node representing every title starting with "alp". However, a plain trie that stores titles only at word endings still has to traverse the entire subtree below 'a' (potentially thousands of nodes) and sort them when the user types "a".

    We make queries near-instant with two simple upgrades:

    • Cache top_titles at every node: constraints say 1 <= limit <= 50, so each TrieNode stores at most MAX_LIMIT = 50 winning titles under its prefix.
    • Insert titles in pre-sorted rank order: sort all deduplicated titles once up front by (-popularity, title). When we insert them into the trie in that exact order, the first 50 titles to pass through any node are automatically that prefix's best 50 titles in final sorted order — no per-node sorting or heap needed!
    Example 2 deduplicated and sorted by (-popularity, title):
      1. "Mesh Routing" (90)   2. "Metrics Overview" (90)   3. "metrics alerts" (75)
    
    Trie paths (lowercase edges) and cached top_titles at each node:
      (root)  top_titles = ["Mesh Routing", "Metrics Overview", "metrics alerts"]
       └── 'm' -> 'e'           top_titles = ["Mesh Routing", "Metrics Overview", "metrics alerts"]
                   ├── 's' -> ... top_titles = ["Mesh Routing"]
                   └── 't' -> ... top_titles = ["Metrics Overview", "metrics alerts"]
    
  3. Build the deduplicated, rank-ordered trie index

    Construction runs in three clean phases inside __init__:

    1. Build max_popularity[title] to collapse duplicate identical titles to their highest score.
    2. Sort (-popularity, title) tuples once. Negating popularity flips larger numbers to smaller negative numbers (-200 < -150), so Python's ascending tuple sort orders by highest popularity first and breaks ties by title ascending in one pass.
    3. Walk each title in lowercase (title.lower()) down from self.root, offering the original-case title to self.root (so an empty prefix "" works too) and to every character node along the path while len(node.top_titles) < 50.
    # Constraints guarantee 1 <= limit <= 50, so no trie node ever needs more than 50 titles.
    MAX_LIMIT = 50
    
    
    class TrieNode:
        def __init__(self):
            # children: {lowercase_char: child_TrieNode}, e.g. {"c": TrieNode(), "b": TrieNode()}
            self.children: Dict[str, "TrieNode"] = {}
            # top_titles: up to MAX_LIMIT original-case titles under this prefix, best-ranked first
            self.top_titles: List[str] = []
    
    
    class PrefixSearchEngine:
        def __init__(self, titles: List[Tuple[str, int]]):
            # Phase 1: Deduplicate identical title strings, keeping the highest popularity score.
            # max_popularity: {exact_title: highest_popularity}, e.g. {"Notes": 50, "notes": 30}
            max_popularity: Dict[str, int] = {}
            for title, popularity in titles:
                if title not in max_popularity or popularity > max_popularity[title]:
                    max_popularity[title] = popularity
    
            # Phase 2: Sort unique titles globally once by:
            #   1) popularity descending (negating popularity turns max-first into min-first)
            #   2) original title ascending (standard lexicographical tie-breaker)
            ranked_entries: List[Tuple[int, str]] = []
            for title, popularity in max_popularity.items():
                ranked_entries.append((-popularity, title))
            ranked_entries.sort()
    
            # Phase 3: Insert titles in rank order so every node's `top_titles` fills up pre-sorted.
            self.root = TrieNode()
            for _, title in ranked_entries:
                self._insert(title)
    
            # Highest non-stale request_id processed so far (valid request IDs start at 1).
            self.max_request_id = 0
    
        def _insert(self, title: str) -> None:
            node = self.root
            # Also offer to root so an empty prefix "" returns the global top titles.
            self._offer(node, title)
            for ch in title.lower():
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
                self._offer(node, title)
    
        def _offer(self, node: TrieNode, title: str) -> None:
            if len(node.top_titles) < MAX_LIMIT:
                node.top_titles.append(title)
    
  4. Answer queries in O(len(prefix) + limit) and reject stale IDs

    Look carefully at the order of operations inside query:

    1. Check request_id <= self.max_request_id first: if true, return None without changing self.max_request_id. Never overwrite self.max_request_id on a stale request — otherwise, after id = 10 and stale id = 4, a late id = 7 would wrongly beat 4!
    2. Update self.max_request_id = request_id before walking the trie: even if the user types "zzzz" and gets [], request 10 was processed, so a delayed request 9 arriving afterward must still be rejected as stale.
    3. Walk prefix.lower() and slice node.top_titles[:limit]: if any character edge is missing, return []. Slicing creates a new list copy so caller edits cannot corrupt our cached top_titles.
        def query(self, prefix: str, request_id: int, limit: int = 5) -> Optional[List[str]]:
            # Reject out-of-order or duplicate request IDs without altering max_request_id.
            if request_id <= self.max_request_id:
                return None
    
            # Record the new watermark BEFORE walking the trie: a valid query that matches
            # zero titles still counts as processed and must invalidate older in-flight IDs.
            self.max_request_id = request_id
    
            node = self.root
            for ch in prefix.lower():
                if ch not in node.children:
                    return []
                node = node.children[ch]
    
            # Slicing returns a fresh list copy so caller mutations cannot corrupt the trie.
            return node.top_titles[:limit]
    
  5. Wire up the judge runner

    The judge entry point prefix_search_engine(titles, operations, arguments) instantiates one PrefixSearchEngine and dispatches each "query" call, honoring the default limit = 5 whenever args has only [prefix, request_id].

    def prefix_search_engine(
        titles: List[Tuple[str, int]],
        operations: List[str],
        arguments: List[List[object]],
    ) -> List[Optional[List[str]]]:
        engine = PrefixSearchEngine(titles)
        results: List[Optional[List[str]]] = []
        for op, args in zip(operations, arguments):
            if op != "query":
                raise ValueError(f"unknown operation: {op}")
            prefix = args[0]
            request_id = args[1]
            if len(args) > 2:
                results.append(engine.query(prefix, request_id, args[2]))
            else:
                results.append(engine.query(prefix, request_id))
        return results
    
  6. Walk through Example 1

    Sorting the five unique engineering titles by (-popularity, title) produces:

    1. "Database Failover Runbook" (210)
    2. "deploy preview service"    (140)
    3. "Deploy Canary Checklist"   (85)
    4. "Deploy Pipeline Guide"     (85)
    5. "Docker Base Images"        (60)
    

    Inserting them in that order fills node "d" with all 5 in that exact order, and node "dep" with [2, 3, 4]. Now replay the three queries:

    Call                      | ID check (vs max_id) | max_id after | Returned
    --------------------------+----------------------+--------------+------------------------------------------------------
    query("dep",    id=2, 3)  | 2 > 0  (fresh)       | 2            | ["deploy preview service",
                              |                      |              |  "Deploy Canary Checklist", "Deploy Pipeline Guide"]
    query("d",      id=5, 2)  | 5 > 2  (fresh)       | 5            | ["Database Failover Runbook", "deploy preview service"]
    query("deploy", id=4, 5)  | 4 <= 5 (STALE!)      | 5 (unchanged)| None
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Constraints guarantee 1 <= limit <= 50, so no trie node ever needs more than 50 titles.
    MAX_LIMIT = 50
    
    
    class TrieNode:
        def __init__(self):
            # children: {lowercase_char: child_TrieNode}, e.g. {"c": TrieNode(), "b": TrieNode()}
            self.children: Dict[str, "TrieNode"] = {}
            # top_titles: up to MAX_LIMIT original-case titles under this prefix, best-ranked first
            self.top_titles: List[str] = []
    
    
    class PrefixSearchEngine:
        def __init__(self, titles: List[Tuple[str, int]]):
            # Phase 1: Deduplicate identical title strings, keeping the highest popularity score.
            # max_popularity: {exact_title: highest_popularity}, e.g. {"Notes": 50, "notes": 30}
            max_popularity: Dict[str, int] = {}
            for title, popularity in titles:
                if title not in max_popularity or popularity > max_popularity[title]:
                    max_popularity[title] = popularity
    
            # Phase 2: Sort unique titles globally once by:
            #   1) popularity descending (negating popularity turns max-first into min-first)
            #   2) original title ascending (standard lexicographical tie-breaker)
            ranked_entries: List[Tuple[int, str]] = []
            for title, popularity in max_popularity.items():
                ranked_entries.append((-popularity, title))
            ranked_entries.sort()
    
            # Phase 3: Insert titles in rank order so every node's `top_titles` fills up pre-sorted.
            self.root = TrieNode()
            for _, title in ranked_entries:
                self._insert(title)
    
            # Highest non-stale request_id processed so far (valid request IDs start at 1).
            self.max_request_id = 0
    
        def _insert(self, title: str) -> None:
            node = self.root
            # Also offer to root so an empty prefix "" returns the global top titles.
            self._offer(node, title)
            for ch in title.lower():
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
                self._offer(node, title)
    
        def _offer(self, node: TrieNode, title: str) -> None:
            if len(node.top_titles) < MAX_LIMIT:
                node.top_titles.append(title)
    
        def query(self, prefix: str, request_id: int, limit: int = 5) -> Optional[List[str]]:
            # Reject out-of-order or duplicate request IDs without altering max_request_id.
            if request_id <= self.max_request_id:
                return None
    
            # Record the new watermark BEFORE walking the trie: a valid query that matches
            # zero titles still counts as processed and must invalidate older in-flight IDs.
            self.max_request_id = request_id
    
            node = self.root
            for ch in prefix.lower():
                if ch not in node.children:
                    return []
                node = node.children[ch]
    
            # Slicing returns a fresh list copy so caller mutations cannot corrupt the trie.
            return node.top_titles[:limit]
    
    
    def prefix_search_engine(
        titles: List[Tuple[str, int]],
        operations: List[str],
        arguments: List[List[object]],
    ) -> List[Optional[List[str]]]:
        engine = PrefixSearchEngine(titles)
        results: List[Optional[List[str]]] = []
        for op, args in zip(operations, arguments):
            if op != "query":
                raise ValueError(f"unknown operation: {op}")
            prefix = args[0]
            request_id = args[1]
            if len(args) > 2:
                results.append(engine.query(prefix, request_id, args[2]))
            else:
                results.append(engine.query(prefix, request_id))
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine organizing an engineering documentation catalog as nested letter-by-letter folders ("d/" -> "de/" -> "dep/"), and taping a pre-sorted "Top 50 Most Popular" shortlist card onto the front of every single folder. That nested folder tree is a trie (prefix tree) — a tree data structure where each edge represents one character and every node corresponds to a prefix shared by all strings in its subtree. When a user types "dep", we simply step down three folders ('d' -> 'e' -> 'p') and read the first limit titles off that folder's card, while a single integer watermark (max_request_id) immediately drops any out-of-order network request carrying an older ticket number.

Scanning every title on each keystroke is too slow because typing a 10-letter query across 50,000 titles would trigger half a million string comparisons plus repeated sorting. Even a basic trie that stores titles only at complete-word nodes is still slow on short prefixes like "d", because it has to walk thousands of descendant nodes and sort them at query time. By sorting the deduplicated catalog once up front by (-popularity, title) and inserting titles in that exact rank order, the first 50 titles to visit any node automatically fill its shortlist in final sorted order with zero per-node sorting.

Trace Example 2 ([("Metrics Overview", 40), ("Metrics Overview", 90), ("metrics alerts", 75), ("Mesh Routing", 90)]): 1. Deduplicate "Metrics Overview" to 90, then sort once by (-popularity, title) -> ["Mesh Routing" (90), "Metrics Overview" (90), "metrics alerts" (75)]. 2. Insert in that order along lowercase characters: node "me" caches top_titles = ["Mesh Routing", "Metrics Overview", "metrics alerts"]. 3. query("me", request_id=1) sees 1 > 0, sets max_request_id = 1, and returns all three; query("zzz", request_id=3, limit=4) advances max_request_id = 3 and returns []; finally query("me", request_id=2, limit=2) sees 2 <= 3 and returns None.

Complexity

Let M be the raw input list length, N the number of unique titles (N <= M), S the sum of character lengths across all N unique titles, p the query prefix length, and k the query limit (k <= 50).

  • Initialization time — O(M + N log N * L_avg + S): We scan all M input pairs once to deduplicate in a hash map (O(M)), sort N unique titles where each tuple comparison compares up to L_avg characters (O(N log N * L_avg)), and walk all S characters of the unique titles once through the trie doing O(1) dictionary lookups and list appends at each step (O(S)).
  • Query time — O(p + k): Stale queries return None in O(1) time; fresh queries take at most p dictionary lookups down prefix.lower() plus O(k) time to slice at most k string references — completely independent of N!
  • Space — O(S): The trie creates at most S + 1 TrieNode objects (fewer when titles share prefixes like "Deploy "), and each unique title appends an 8-byte string reference (not a character copy) to at most len(title) + 1 node lists, totaling at most S + N list entries across the entire trie.

Edge cases

  • Equal or out-of-order request_id: request_id <= max_request_id treats duplicate IDs (5 after 5) as stale (None), and stale queries never overwrite max_request_id (so after 10, both 4 and 7 return None).
  • Valid query with zero matches: Returns [] (distinct from None for stale) and still updates max_request_id so earlier delayed requests cannot sneak through afterward.
  • Empty prefix "" and full-title prefix: Because _insert also offers every title to self.root, prefix = "" returns the global top limit titles; a prefix equal to an entire title returns that title (plus any longer extensions).
  • Duplicate titles vs. case-variant titles: Exact duplicates keep their maximum popularity, whereas "Notes" and "notes" are distinct strings that can both appear in results.
  • Popularity ties with mixed case: Python's standard < string comparison compares Unicode code points, placing uppercase ASCII ('A' = 65) ahead of lowercase ('a' = 97), e.g., "Apricot" before "apple".
  • Default limit omitted: Defaults cleanly to 5 when arguments passes only [prefix, request_id].

Common mistakes

  • Returning None when a prefix matches nothing: Conflates "no matching documents" ([]) with "discarded stale request" (None).
  • Setting self.max_request_id = request_id unconditionally (or only after matches are found): Updating on every call lets id=10 -> id=4 -> id=7 accept 7; updating only on non-empty matches lets an older ID slip through right after a query that returned [].
  • Storing lowercased titles inside top_titles: Lowercasing must only be used for trie edge navigation; the payload stored in top_titles must preserve original casing.
  • Keeping the first or last duplicate instead of max popularity: Overwriting best[title] = popularity blindly loses higher earlier scores.
  • Returning node.top_titles directly without slicing when limit >= len(node.top_titles): Slicing (node.top_titles[:limit]) always creates a shallow copy so external caller edits cannot mutate internal trie state.

Alternative approaches

  • Radix tree (compressed trie): A radix tree merges every single-child chain of characters (such as 'r' -> 'u' -> 'n' -> 'b' -> 'o' -> 'o' -> 'k') into one edge labeled "runbook". This shrinks node count from O(S) to O(N) — cutting Python object memory dramatically on long titles — while keeping O(p + k) query speed, at the cost of edge-splitting code during insertion.
  • Sorted array + binary search (bisect): Sort (title.lower(), -popularity, title) and use two binary searches on each query to locate the contiguous range of R titles starting with prefix.lower(), then extract the top k with a min-heap in O(p log N + R log k) time. Memory is tiny (O(N)), and specific prefixes are fast, but 1-letter prefixes like "d" degrade to scanning thousands of entries (R ≈ N).

Follow-up questions

  • How would you support matching prefixes of inner words or arbitrary mid-word substrings instead of only the start of the full title? For inner-word prefix search (e.g., "failover" matching "Database Failover Runbook"), split each title on whitespace/punctuation and insert every word-start suffix ("database failover runbook", "failover runbook", "runbook") into the trie while storing the full original title as the payload, skipping node.top_titles.append(title) if node.top_titles and node.top_titles[-1] == title so repeated word prefixes never list the same title twice at one node. For arbitrary mid-word substrings, build an n-gram inverted index — a hash map from every 3-character slice ("ail", "ilo") to sorted document IDs — intersect the posting lists for the query's trigrams, verify exact substring containment, and return the top-scoring matches.
  • Suppose thousands of catalog edits arrive per minute; how can you incorporate live writes safely without slowing down read queries? Thousands of writes per minute is roughly 20–100 updates per second, so the cleanest way to keep read latency lock-free is copy-on-write snapshot swapping: readers always query an immutable reference to the active PrefixSearchEngine without locks, while a background worker batches updates every 1–2 seconds into a fresh or path-copied trie and atomically swaps the reference. If sub-millisecond write visibility is required instead, guard mutations with a readers-writer lock (allowing many concurrent readers or one exclusive writer): inserts and score increases bubble up only the len(title) + 1 nodes along one path, while deletes/demotions maintain a slightly larger per-node buffer (e.g., top 100) or recompute a depleted node's top 50 by merging its children's top_titles lists.
  • On the browser side, how can standard Web APIs cancel superseded autocomplete requests and prevent out-of-order UI updates? Before firing a new fetch on an input event, call controller.abort() on the previous AbortController (a standard browser API object whose signal cancels an in-flight fetch request and rejects its promise with AbortError, which the catch handler ignores). Because an earlier response can still resolve just before abort() executes, combine AbortController with a client-side monotonic counter (const myId = ++latestRequestId) and only render the dropdown if myId === latestRequestId, paired with debouncing (waiting ~100–150 ms after a keystroke before sending the network call) to reduce server traffic while keeping suggestions responsive.

Follow-up questions

Similar questions

More Charta Health interview questions

All 4 Charta Health questions →