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
PrefixSearchEngine(titles: List[Tuple[str, int]]):- Loads
(title, popularity)entries wheretitleis a non-empty string andpopularityis a positive integer score. - If the exact same
titlestring (case-sensitive) appears more than once, deduplicate it by keeping only its maximumpopularityscore. Titles that differ in letter casing (such as"Guide"and"guide") remain distinct entries.
- Loads
query(prefix: str, request_id: int, limit: int = 5) -> Optional[List[str]]:- Out-of-order filtering: Track the largest
request_idaccepted so far (starting from0). Wheneverrequest_idis less than or equal to that highest processed ID, treat the call as stale: leave the watermark unchanged and returnNone. - Prefix matching: Match every unique title whose full text begins with
prefixignoring letter case (title.lower().startswith(prefix.lower())), while returning each matched title in its original casing. - Ranking & truncation: Order matches by
popularitydescending first, breaking ties by standard ascending string order (<on the original-casedtitle), and return at mostlimittitles. If a non-stale query matches zero titles, update the watermark and return[].
- Out-of-order filtering: Track the largest
prefix_search_engine(titles, operations, arguments):- Instantiates
PrefixSearchEngine(titles)once and runs each"query"operation usingarguments[i]([prefix, request_id]or[prefix, request_id, limit]), returning the list of outputs in call order.
- Instantiates
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; score140ranks first, and the tie at85orders"Deploy Canary Checklist"ahead of"Deploy Pipeline Guide". - Call 2 (
request_id = 5): Fresh (5 > 2). All five titles begin with"d", andlimit = 2keeps scores210and140. - Call 3 (
request_id = 4): Stale (4 <= 5), soNoneis returned immediately.
- Call 1 (
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 score90and ties with"Mesh Routing"("Mesh Routing" < "Metrics Overview"). Call 1 uses the defaultlimit = 5; Call 2 matches nothing ([]) while advancing the watermark to3; Call 3 (2 <= 3) is rejected as stale (None).
Constraints
- At most
50,000unique titles, with average length at most80characters 0 <= len(prefix) <= 501 <= request_id <= 10^91 <= limit <= 50(defaults to5when omitted)
Step-by-step walkthrough
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, response2can arrive after response3has already been processed; showing response2would overwrite newer results with stale ones.Our
PrefixSearchEngineloads(title, popularity)pairs once and answersquery(prefix, request_id, limit=5)under five rules:- Stale protection: track the highest
request_idprocessed so far (max_request_id, initialized to0). Ifrequest_id <= max_request_id, returnNoneimmediately and leavemax_request_idunchanged. - 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. - 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). - 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"). - Empty matches vs. stale queries: a valid query with no matching titles returns
[](neverNone, which means stale) and still updatesmax_request_id.
- Stale protection: track the highest
Why scanning on every keystroke is too slow — and how a cached trie fixes it
A naive implementation scans all
Ntitles on every keystroke, checkstitle.lower().startswith(prefix.lower()), and sorts all matches. WithN = 50,000titles 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_titlesat every node: constraints say1 <= limit <= 50, so eachTrieNodestores at mostMAX_LIMIT = 50winning 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"]- Cache
Build the deduplicated, rank-ordered trie index
Construction runs in three clean phases inside
__init__:- Build
max_popularity[title]to collapse duplicate identical titles to their highest score. - Sort
(-popularity, title)tuples once. Negatingpopularityflips larger numbers to smaller negative numbers (-200 < -150), so Python's ascending tuple sort orders by highest popularity first and breaks ties bytitleascending in one pass. - Walk each title in lowercase (
title.lower()) down fromself.root, offering the original-casetitletoself.root(so an empty prefix""works too) and to every character node along the path whilelen(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)- Build
Answer queries in O(len(prefix) + limit) and reject stale IDs
Look carefully at the order of operations inside
query:- Check
request_id <= self.max_request_idfirst: if true, returnNonewithout changingself.max_request_id. Never overwriteself.max_request_idon a stale request — otherwise, afterid = 10and staleid = 4, a lateid = 7would wrongly beat4! - Update
self.max_request_id = request_idbefore walking the trie: even if the user types"zzzz"and gets[], request10was processed, so a delayed request9arriving afterward must still be rejected as stale. - Walk
prefix.lower()and slicenode.top_titles[:limit]: if any character edge is missing, return[]. Slicing creates a new list copy so caller edits cannot corrupt our cachedtop_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]- Check
Wire up the judge runner
The judge entry point
prefix_search_engine(titles, operations, arguments)instantiates onePrefixSearchEngineand dispatches each"query"call, honoring the defaultlimit = 5wheneverargshas 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 resultsWalk 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)| NoneComplete 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 allMinput pairs once to deduplicate in a hash map (O(M)), sortNunique titles where each tuple comparison compares up toL_avgcharacters (O(N log N * L_avg)), and walk allScharacters of the unique titles once through the trie doingO(1)dictionary lookups and list appends at each step (O(S)). - Query time —
O(p + k): Stale queries returnNoneinO(1)time; fresh queries take at mostpdictionary lookups downprefix.lower()plusO(k)time to slice at mostkstring references — completely independent ofN! - Space —
O(S): The trie creates at mostS + 1TrieNodeobjects (fewer when titles share prefixes like"Deploy "), and each unique title appends an 8-byte string reference (not a character copy) to at mostlen(title) + 1node lists, totaling at mostS + Nlist entries across the entire trie.
Edge cases
- Equal or out-of-order
request_id:request_id <= max_request_idtreats duplicate IDs (5after5) as stale (None), and stale queries never overwritemax_request_id(so after10, both4and7returnNone). - Valid query with zero matches: Returns
[](distinct fromNonefor stale) and still updatesmax_request_idso earlier delayed requests cannot sneak through afterward. - Empty prefix
""and full-title prefix: Because_insertalso offers every title toself.root,prefix = ""returns the global toplimittitles; 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
limitomitted: Defaults cleanly to5whenargumentspasses only[prefix, request_id].
Common mistakes
- Returning
Nonewhen a prefix matches nothing: Conflates "no matching documents" ([]) with "discarded stale request" (None). - Setting
self.max_request_id = request_idunconditionally (or only after matches are found): Updating on every call letsid=10 -> id=4 -> id=7accept7; 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 intop_titlesmust preserve original casing. - Keeping the first or last duplicate instead of
maxpopularity: Overwritingbest[title] = popularityblindly loses higher earlier scores. - Returning
node.top_titlesdirectly without slicing whenlimit >= 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 fromO(S)toO(N)— cutting Python object memory dramatically on long titles — while keepingO(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 ofRtitles starting withprefix.lower(), then extract the topkwith a min-heap inO(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, skippingnode.top_titles.append(title)ifnode.top_titles and node.top_titles[-1] == titleso 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
PrefixSearchEnginewithout 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 thelen(title) + 1nodes 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'stop_titleslists. - On the browser side, how can standard Web APIs cancel superseded autocomplete requests and prevent out-of-order UI updates? Before firing a new
fetchon an input event, callcontroller.abort()on the previous AbortController (a standard browser API object whosesignalcancels an in-flightfetchrequest and rejects its promise withAbortError, which thecatchhandler ignores). Because an earlier response can still resolve just beforeabort()executes, combineAbortControllerwith a client-side monotonic counter (const myId = ++latestRequestId) and only render the dropdown ifmyId === 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
- How would you support matching prefixes of inner words or arbitrary mid-word substrings instead of only the start of the full title?
- Suppose thousands of catalog edits arrive per minute; how can you incorporate live writes safely without slowing down read queries?
- On the browser side, how can standard Web APIs cancel superseded autocomplete requests and prevent out-of-order UI updates?
Similar questions
- Thread-Safe Lazy Token Bucket Rate Limiter
- Past System Deep Dive and Fit for Charta Health
- Semantic Caching and Coalescing for Clinical Extraction
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination