Indexed Whole-Word and Sequential Phrase Search Over Documents
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Given an indexed corpus documents (where document i is the string documents[i]) and a batch of search queries specified by parallel arrays operations and arguments, build an in-memory search index once and evaluate every query in order:
def search_documents(
documents: List[str],
operations: List[str],
arguments: List[List[str]],
) -> List[List[int]]:
Tokenization & Matching Rules
Apply the exact same normalization rule to every document string and every query string:
- Word tokens: A token is a maximal contiguous run of alphanumeric characters (
ch.isalnum(), i.e., letters and digits), converted to lowercase. - Separators: Every non-alphanumeric character—spaces, punctuation, hyphens, periods, and symbols—acts purely as a token boundary. For instance,
"End-to-End 2.0!"splits into["end", "to", "end", "2", "0"]. - Whole-token matching: Tokens match only as complete words, never as substrings (
"cloud"does not match"cloudy"). - Query construction: For query
k, form the raw query text by joiningarguments[k]with single spaces (" ".join(arguments[k])), then tokenize it. If tokenization produces zero tokens (for example""or"???"), the query matches nothing and yields[].
Supported Operations
operations[k] == "word"— Return every document IDdoc_idwhose token stream contains the queried token. (If internal punctuation splits the query into multiple tokens, require all of those tokens to appear in sequence just like"phrase".)operations[k] == "phrase"— Let the tokenized query be[w_0, w_1, ..., w_{m-1}]. Return every document IDdoc_idwhose token streamTcontains strictly increasing token indicesi_0 < i_1 < ... < i_{m-1}withT[i_r] == w_rfor all0 <= r < m. Other tokens may appear between matched positions, and matches may span across punctuation. When a token repeats in the phrase, each copy must match a separate, strictly later occurrence inT.
For every query, list each matching doc_id at most once, sorted in strictly ascending order.
Examples
Example 1
Input:
documents = [
"Cloud servers store logs.",
"Every CLOUD backup stores snapshots.",
"Cloudy skies ahead."
]
operations = ["word", "phrase"]
arguments = [["cloud"], ["cloud snapshots"]]
Output: [[0, 1], [1]]
Walk-through:
- Document 0 tokenizes to ["cloud", "servers", "store", "logs"], document 1 to ["every", "cloud", "backup", "stores", "snapshots"], and document 2 to ["cloudy", "skies", "ahead"].
- "word" for "cloud" matches documents 0 and 1, skipping document 2 because "cloudy" is a distinct whole token.
- "phrase" for "cloud snapshots" matches document 1 ("cloud" at index 1 precedes "snapshots" at index 4, with intervening words permitted).
Example 2
Input:
documents = [
"Step by step, build the index.",
"Build one step by dusk."
]
operations = ["word", "phrase"]
arguments = [["step"], ["step by step"]]
Output: [[0, 1], [0]]
Walk-through:
- Both documents contain the token "step", so the "word" query returns [0, 1].
- "step by step" requires two distinct occurrences of "step" separated by "by" (0 < 1 < 2 in document 0). Document 1 has "step" at index 2 and "by" at index 3, with no second "step" afterward, so only [0] matches.
Example 3
Input:
documents = [
"end-to-end encryption",
"End to end testing suite",
"open ended design",
"encryption from end"
]
operations = ["word", "phrase", "phrase"]
arguments = [["end"], ["end suite"], ["end to end"]]
Output: [[0, 1, 3], [1], [0, 1]]
Walk-through:
- Hyphens split "end-to-end" into ["end", "to", "end"]. Documents 0, 1, and 3 contain "end" (document 2 only has "ended"), each reported once in ascending order: [0, 1, 3].
- "end suite" appears in order only in document 1 ([1]), while "end to end" matches both document 0 and document 1 ([0, 1]).
Constraints
0 <= len(documents) <= 10^4, with at most10^6characters across all documents combined.1 <= len(operations) == len(arguments) <= 10^4.- Each
operations[k]is either"word"or"phrase". 1 <= len(arguments[k]) <= 10, with total query characters up to10^5.- Precompute an index over
documentsonce so queries do not rescan the raw corpus text.
Step-by-step walkthrough
Clarify tokenization and matching rules
Before designing the index, let's pin down the exact rules defined by the specification and examples:
- What counts as a word? Maximal contiguous runs of letters and digits (
ch.isalnum()), converted to lowercase. Every other character (spaces, commas, periods, hyphens) separates words, so"end-to-end"becomes["end", "to", "end"], and"end"matches whole token"end"rather than"ended". - Same tokenizer everywhere: Both documents and queries pass through the exact same
tokenizefunction so"CLOUD"matches"cloud"and"logs."matches"logs". - Result format: Return matching document IDs (
0, 1, ...), each listed at most once, in strictly ascending order. An empty or punctuation-only query ("","???") produces zero tokens and returns[]. - Ordered phrase matching: The phrase's words must appear in the same left-to-right sequence inside the document, with other words allowed in between (for example,
"cloud snapshots"matches"Every CLOUD backup stores snapshots.", and"end suite"matches"End to end testing suite"). Repeated words in a phrase ("step by step") must match distinct, strictly increasing token positions.
- What counts as a word? Maximal contiguous runs of letters and digits (
Why rescanning every document is too slow
A brute-force implementation tokenizes every document from scratch on every single query and advances a pointer across the phrase:
def find_phrase_naive(documents: list, phrase: str) -> list: wanted = tokenize(phrase) if not wanted: return [] matches = [] for doc_id, text in enumerate(documents): j = 0 for word in tokenize(text): if j < len(wanted) and word == wanted[j]: j += 1 if j == len(wanted): matches.append(doc_id) return matchesWhile simple and helpful for cross-checking tests, each query inspects every character of every document (
O(C)time forCtotal corpus characters). Across 10,000 documents and 10,000 queries, rescanning repeats billions of character checks even when a target word only appears in two documents.Build a positional inverted index
Like the alphabetical index at the back of a textbook, an inverted index flips
document -> wordsaround intoword -> documents. Because phrase queries also need to verify token order without re-reading raw text, we record the exact token positions of each word inside each document right from the start:Documents: doc 0: "Cloud servers store logs." -> [0:"cloud", 1:"servers", 2:"store", 3:"logs"] doc 1: "Every CLOUD backup stores snapshots." -> [0:"every", 1:"cloud", 2:"backup", 3:"stores", 4:"snapshots"] Positional inverted index (`self.postings`): "cloud" -> {0: [0], 1: [1]} "servers" -> {0: [1]} "store" -> {0: [2]} "logs" -> {0: [3]} "every" -> {1: [0]} "backup" -> {1: [2]} "stores" -> {1: [3]} "snapshots" -> {1: [4]}Notice two automatic ordering guarantees: because we loop
doc_id = 0, 1, ...andposition = 0, 1, ...in order, and Python dictionaries preserve insertion order, every inner dict's keys (doc_ids) and everypositionslist are already sorted in strictly ascending order with zero sorting calls!For
find_word(word), a single-token query is just one dictionary lookuplist(self.postings.get(target, {})). If internal punctuation splits the input into multiple tokens (such as"end-to-end"), we delegate tofind_phrase(word).def tokenize(text: str) -> List[str]: """Split `text` into lowercase alphanumeric words; all other characters act as separators.""" words: List[str] = [] current_chars: List[str] = [] for ch in text: if ch.isalnum(): current_chars.append(ch) elif current_chars: # Non-alphanumeric character ends the word currently being built. words.append("".join(current_chars).lower()) current_chars = [] if current_chars: words.append("".join(current_chars).lower()) return words class DocumentIndex: def __init__(self, documents: List[str]): self.postings: Dict[str, Dict[int, List[int]]] = {} for doc_id, text in enumerate(documents): tokens = tokenize(text) for position, word in enumerate(tokens): if word not in self.postings: self.postings[word] = {} by_doc = self.postings[word] if doc_id not in by_doc: by_doc[doc_id] = [] by_doc[doc_id].append(position) def find_word(self, word: str) -> List[int]: query_words = tokenize(word) if not query_words: return [] if len(query_words) > 1: return self.find_phrase(word) target = query_words[0] return list(self.postings.get(target, {}))Narrow phrase candidates from the rarest word first
Before checking token positions in
find_phrase, observe that any matching document must contain every distinct word in the phrase.Suppose a phrase is
"the snapshots", where"the"appears in5,000documents and"snapshots"appears in2documents ([14, 809]). If we sort the per-word dictionaries by length (len(by_doc)) and initializecandidatesfrom"snapshots", we only run2O(1)dictionary membership checks (14 in postings["the"],809 in postings["the"]) instead of5,000!Phrase: "every rare cloud" postings["every"] has 5,000 docs postings["cloud"] has 120 docs postings["rare"] has 2 docs: {7: [...], 42: [...]} Sort by doc count -> start from "rare" candidates [7, 42]: Filter by "cloud": keep doc_id if doc_id in postings["cloud"] -> [42] Filter by "every": keep doc_id if doc_id in postings["every"] -> [42]Because
candidatesstarts in ascendingdoc_idorder and we filter it left to right, the surviving candidates stay sorted in ascending order.class _CandidateDemo(DocumentIndex): def _docs_with_all(self, words: List[str]) -> List[int]: distinct_words = set(words) doc_maps: List[Dict[int, List[int]]] = [] for word in distinct_words: if word not in self.postings: return [] doc_maps.append(self.postings[word]) doc_maps.sort(key=len) candidates = list(doc_maps[0]) for other_doc_map in doc_maps[1:]: kept: List[int] = [] for doc_id in candidates: if doc_id in other_doc_map: kept.append(doc_id) candidates = kept if not candidates: break return candidatesVerify word order greedily with binary search
Containing every distinct word is necessary, not sufficient:
"encryption from end"contains both"end"and"encryption", yet"end encryption"does not appear in that order. Even trickier, comparing only the first occurrence of each word fails on"b a b"for phrase"a b"(the first"b"is at0 < 1, whereas"a"at1followed by the second"b"at2is a valid match!).How should we choose positions for
words[0], words[1], ...insidedoc_id? Greedily pick the earliest valid position at every step:- Start with
prev_pos = -1. - For each
wordinwords, look up its sortedpositions = self.postings[word][doc_id]and find the smallest position strictly greater thanprev_posusingbisect_right(positions, prev_pos). - Why is greedy guaranteed never to miss a valid match? Because if any valid chain
p_0 < p_1 < ...exists, replacingp_0with an even smaller positionp'_0 <= p_0still satisfiesp'_0 < p_1— choosing earlier can only leave more room for the remaining tokens! - Why
bisect_rightinstead ofbisect_left?bisect_rightrequirespositions[idx] > prev_pos(strict inequality), so in"step step"the second"step"cannot reuse the exact same position as the first"step".
Document 0 (Example 2): "Step by step, build the index." Positions: step: [0, 2], by: [1], build: [3], the: [4], index: [5] Verify phrase ["step", "by", "step"]: Start: prev_pos = -1 "step" in [0, 2] -> first > -1 is 0 (prev_pos = 0) "by" in [1] -> first > 0 is 1 (prev_pos = 1) "step" in [0, 2] -> first > 1 is 2 (prev_pos = 2) -> True!class _OrderDemo(DocumentIndex): def find_phrase(self, phrase: str) -> List[int]: query_words = tokenize(phrase) if not query_words: return [] matching_docs: List[int] = [] for doc_id in self._docs_with_all(query_words): if self._in_order(doc_id, query_words): matching_docs.append(doc_id) return matching_docs def _in_order(self, doc_id: int, words: List[str]) -> bool: prev_pos = -1 for word in words: positions = self.postings[word][doc_id] idx = bisect_right(positions, prev_pos) if idx == len(positions): return False prev_pos = positions[idx] return True- Start with
Wire up the query runner
search_documentsbuildsDocumentIndex(documents)once, then dispatches each"word"or"phrase"operation against the precomputed index. Joiningargswith" "cleanly supports queries passed either as["cloud snapshots"]or["cloud", "snapshots"].def search_documents( documents: List[str], operations: List[str], arguments: List[List[str]], ) -> List[List[int]]: index = DocumentIndex(documents) results: List[List[int]] = [] for operation, args in zip(operations, arguments): query_text = " ".join(args) if operation == "word": results.append(index.find_word(query_text)) elif operation == "phrase": results.append(index.find_phrase(query_text)) else: raise ValueError(f"unknown operation: {operation!r}") return resultsWalk through Example 3
Input documents: doc 0: "end-to-end encryption" -> [0:"end", 1:"to", 2:"end", 3:"encryption"] doc 1: "End to end testing suite" -> [0:"end", 1:"to", 2:"end", 3:"testing", 4:"suite"] doc 2: "open ended design" -> [0:"open", 1:"ended", 2:"design"] doc 3: "encryption from end" -> [0:"encryption", 1:"from", 2:"end"] Queries: 1. word "end": postings["end"] = {0: [0, 2], 1: [0, 2], 3: [2]} (doc 2 has "ended", not "end") -> [0, 1, 3] 2. phrase "end suite": candidates with {"end", "suite"} = [1] doc 1: end@0 < suite@4 (True) -> [1] 3. phrase "end to end": candidates with {"end", "to"} = [0, 1] doc 0 and doc 1 both match positions 0 < 1 < 2 -> [0, 1]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from bisect import bisect_right def tokenize(text: str) -> List[str]: """Split `text` into lowercase alphanumeric words; all other characters act as separators.""" words: List[str] = [] current_chars: List[str] = [] for ch in text: if ch.isalnum(): current_chars.append(ch) elif current_chars: # Non-alphanumeric character ends the word currently being built. words.append("".join(current_chars).lower()) current_chars = [] if current_chars: words.append("".join(current_chars).lower()) return words class DocumentIndex: def __init__(self, documents: List[str]): # postings: Dict[word, Dict[doc_id, List[position]]] # Example: {"cloud": {0: [0], 1: [1, 4]}} # Because we scan `doc_id` 0..N-1 and `position` 0..M-1 in order, both the # inner dict keys (`doc_id`) and each position list are naturally ascending. self.postings: Dict[str, Dict[int, List[int]]] = {} for doc_id, text in enumerate(documents): tokens = tokenize(text) for position, word in enumerate(tokens): if word not in self.postings: self.postings[word] = {} by_doc = self.postings[word] if doc_id not in by_doc: by_doc[doc_id] = [] by_doc[doc_id].append(position) def find_word(self, word: str) -> List[int]: """Part 1: return ascending document IDs containing `word` as a whole token.""" query_words = tokenize(word) if not query_words: return [] if len(query_words) > 1: # Punctuation inside `word` (e.g. "end-to-end") produces multiple tokens, # so delegate to ordered phrase search. return self.find_phrase(word) target = query_words[0] # Dict keys are already stored in ascending `doc_id` insertion order. return list(self.postings.get(target, {})) def find_phrase(self, phrase: str) -> List[int]: """Part 2: return ascending document IDs where `phrase` tokens appear in order.""" query_words = tokenize(phrase) if not query_words: return [] matching_docs: List[int] = [] for doc_id in self._docs_with_all(query_words): if self._in_order(doc_id, query_words): matching_docs.append(doc_id) return matching_docs def _docs_with_all(self, words: List[str]) -> List[int]: """Intersect document sets for all distinct words, starting from the rarest word.""" distinct_words = set(words) doc_maps: List[Dict[int, List[int]]] = [] for word in distinct_words: if word not in self.postings: # If any required word never appears in the corpus, no document can match. return [] doc_maps.append(self.postings[word]) # Sort by number of documents so our initial candidate list is as tiny as possible. doc_maps.sort(key=len) candidates = list(doc_maps[0]) for other_doc_map in doc_maps[1:]: kept: List[int] = [] for doc_id in candidates: # O(1) dict key check preserves the ascending order of `candidates`. if doc_id in other_doc_map: kept.append(doc_id) candidates = kept if not candidates: break return candidates def _in_order(self, doc_id: int, words: List[str]) -> bool: """Greedily pick the earliest occurrence of each phrase word strictly after `prev_pos`.""" prev_pos = -1 for word in words: positions = self.postings[word][doc_id] # `bisect_right` finds the first index `idx` with `positions[idx] > prev_pos` # (strictly greater, so repeated words like "step step" must use distinct positions). idx = bisect_right(positions, prev_pos) if idx == len(positions): return False prev_pos = positions[idx] return True def search_documents( documents: List[str], operations: List[str], arguments: List[List[str]], ) -> List[List[int]]: index = DocumentIndex(documents) results: List[List[int]] = [] # Build the index once, then answer every word or phrase query against it. for operation, args in zip(operations, arguments): query_text = " ".join(args) if operation == "word": results.append(index.find_word(query_text)) elif operation == "phrase": results.append(index.find_phrase(query_text)) else: raise ValueError(f"unknown operation: {operation!r}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of the alphabetical index at the back of a textbook: instead of re-reading all 500 pages every time you want to look up a topic, you flip to the back and immediately see which pages mention that term. Here we construct a positional inverted index (a lookup table mapping each unique word to the documents containing it and the exact token positions where it appears inside each document), after passing both documents and queries through tokenization (splitting raw text into normalized lowercase runs of letters and digits so punctuation and capitalization never get in the way).
The obvious naive approach re-reads and re-tokenizes every document in the collection on every single query. That works on three tiny strings, but on a corpus of thousands of documents queried repeatedly, scanning millions of characters per query wastes huge amounts of work whenever the queried word only appears in a handful of documents. With our precomputed index, find_word is a single dictionary lookup, and find_phrase checks whether the phrase words form an ordered subsequence (appearing in the same left-to-right order, possibly with other words in between) by first intersecting document sets starting from the rarest word, then advancing prev_pos greedily with binary search (bisect_right, which halves a sorted list repeatedly to find the first position strictly greater than prev_pos in logarithmic time).
Let's trace Example 2 (doc 0 = "Step by step, build the index.", doc 1 = "Build one step by dusk."):
- Tokenization yields
doc 0positionsstep: [0, 2], by: [1], ...anddoc 1positionsstep: [2], by: [3], .... find_word("step"): looks uppostings["step"] = {0: [0, 2], 1: [2]}and returns its keys[0, 1]directly in ascending order.find_phrase("step by step"): intersects candidate docs containing"step"and"by"->[0, 1].- Verify
doc 0:"step"picks0 > -1(prev_pos = 0);"by"picks1 > 0(prev_pos = 1); second"step"runsbisect_right([0, 2], 1), skipping0and picking2 > 1-> match! - Verify
doc 1:"step"picks2,"by"picks3, and[2]has no position> 3-> rejected. Result:[0].
Complexity
Let C be the total number of characters across all documents, W be the total number of word tokens across all documents, and q be the character length of a query. For a phrase of m words (u of them distinct), let k_min be the number of documents containing the rarest word in the phrase, and p be the maximum occurrences of a phrase word inside a single candidate document.
- Index construction (
DocumentIndex.__init__):- Time:
O(C)because every character across all documents is scanned once during tokenization and each of theWword occurrences performs expectedO(1)dictionary lookups and list appends. - Space:
O(W)because every word occurrence stores one integer position in a posting list (the per-word list of matching documents and positions).
- Time:
find_word:O(q)time to tokenize the query plusO(k)time to copy thekmatching document IDs (already stored in ascending order), usingO(k)output space.find_phrase:O(q)time to tokenize,O(u log u)to sort theudistinct words by document frequency, at mostO(u * k_min)expected time to intersect dictionary keys starting from the rarest word, andO(k_min * m * log p)worst-case time to verify thek_mincandidate documents withmbinary searches of costO(log p)each.
Edge cases
- Empty document list or documents with only punctuation (
"!!!"): produce no index entries and cleanly return[]for all queries. - Empty or punctuation-only query (
"","???"): tokenizes to[]and returns[]without matching every document. - Word missing from the entire corpus:
find_wordgets{}and_docs_with_allexits immediately with[]. - Case and punctuation in queries (
"HELLO!","end-to-end"): normalized identically to document text; multi-token inputs tofind_worddelegate tofind_phrase. - Substring false positives (
"cloud"vs"cloudy","end"vs"ended"): avoided because matching operates on whole alphanumeric tokens rather than raw substrings. - Repeated words in a phrase (
"go go","step by step"):bisect_right(positions, prev_pos)enforces strictly increasing positions (pos > prev_pos), so a single"step"in a document cannot satisfy"step by step". - Earlier occurrence trap (
"b a b"for"a b"): handled becausebisect_rightskips"b"at position0and finds the later"b"at position2. - Multiple matches inside the same document (
"end-to-end"): returns each matchingdoc_idonce, in ascending order.
Common mistakes
- Using substring checks (
word in doc_text): falsely matches"cloud"inside"cloudy"or"do"inside"dog". - Applying different normalization to queries than to documents: forgets to strip trailing punctuation or lowercase queries like
"CLOUD"or"logs.". - Checking only the first occurrence of each word (
first_pos["a"] < first_pos["b"]): misses"a b"inside"b a b". - Using
bisect_leftinstead ofbisect_right: allowspositions[idx] == prev_pos, so"step step"falsely matches a document containing only one"step". - Returning unsorted IDs from a Python
setor duplicate IDs per occurrence: breaks the ascending unique-ID contract. - Intersecting candidate lists with
doc_id in other_listinstead of a dict/set: turns candidate filtering fromO(k_min)intoO(k_1 * k_2).
Alternative approaches
- Adjacent-only phrase search: if an interviewer specifies that phrase words must appear at consecutive positions (
s, s + 1, ..., s + m - 1), store each word's positions in aset(alongside the list for the first word) and check whetherall((s + i) in pos_set[i] for i in range(1, m))for any start positionsof the rarest word. - Sorted posting lists with two-pointer / galloping merge: on-disk search engines (like Lucene) store
doc_ids in compressed sorted integer arrays rather than hash maps, intersecting two sorted lists inO(k_1 + k_2)with two pointers orO(k_1 log k_2)with galloping binary search to save hash-table memory overhead.
Follow-up questions
- How would you extend the index to handle live document insertions, updates, and deletions without rebuilding from scratch? Appending a new document with the next sequential
doc_idsimply tokenizes it and appends(doc_id, positions)to each word's posting dict inO(len(doc))time, preserving ascendingdoc_idorder automatically. For deletions, maintain a tombstonedeleted_ids: Set[int]that queries skip inO(1)time per candidate, and periodically compact the index in the background (or store a forwarddoc_id -> Set[word]map to deletedoc_idfrom each word's inner dict immediately). Updating a document marks its olddoc_iddeleted and inserts the updated text under a freshdoc_idso ascending insertion order never breaks. - How could you score and sort matching documents by relevance, such as phrase frequency or match compactness? Count the maximum number of non-overlapping occurrences of the phrase in a candidate document by repeating our greedy
_in_orderwalk in a loop, starting each next match strictly after the end position of the previous match (the same earliest-finish-time greedy choice used in interval scheduling). You can then sort matching documents by descending match count (normalized by document token length, as in BM25/TF-IDF, so long documents do not dominate purely by length) and break ties by smallest match spanend_pos - start_pos:
def count_non_overlapping_matches(index: DocumentIndex, doc_id: int, words: List[str]) -> int:
count = 0
prev_pos = -1
while True:
for word in words:
positions = index.postings[word][doc_id]
idx = bisect_right(positions, prev_pos)
if idx == len(positions):
return count
prev_pos = positions[idx]
count += 1
- When the corpus outgrows a single server's RAM, how should you shard the index across machines, and how does that affect phrase query latency? Use document partitioning (sharding), meaning you split the documents across
Smachines (doc_id % S) so each machine holds a self-contained positional index for its own slice of documents. A coordinator broadcasts the phrase query to allSshards in parallel, each shard runsfind_phraselocally with zero network transfers of position lists, and the coordinator merges theSsorteddoc_idlists inO(r log S)time forrtotal matches (total CPU work equals the single-machine work divided acrossSshards, and latency equals the slowest shard plus one network round-trip; partitioning by word instead would force shards to ship giant position lists for frequent words over the network). - How would you modify phrase verification if consecutive query tokens must lie at most
kpositions apart? If each adjacent pair of phrase words must satisfy1 <= pos[j] - pos[j - 1] <= k, greedy earliest-position alone is no longer sufficient (in"a x a b"withk = 1for"a b","a"at0is too far from"b"at3, whereas"a"at2succeeds!). Instead, maintain the sorted listreachableof valid ending positions after matching the firstjwords; a positionpof wordj + 1is reachable if and only if the largest positionq < pinreachable(found viabisect_left(reachable, p) - 1) satisfiesp - q <= k:
from bisect import bisect_left
def matches_within_k(position_lists: List[List[int]], k: int) -> bool:
if not position_lists or not position_lists[0]:
return False
reachable = position_lists[0]
for positions in position_lists[1:]:
next_reachable: List[int] = []
for p in positions:
idx = bisect_left(reachable, p) # reachable[idx - 1] is the largest q < p
if idx > 0 and p - reachable[idx - 1] <= k:
next_reachable.append(p)
reachable = next_reachable
if not reachable:
return False
return True
Follow-up questions
- How would you extend the index to handle live document insertions, updates, and deletions without rebuilding from scratch?
- How could you score and sort matching documents by relevance, such as phrase frequency or match compactness?
- When the corpus outgrows a single server's RAM, how should you shard the index across machines, and how does that affect phrase query latency?
- How would you modify phrase verification if consecutive query tokens must lie at most `k` positions apart?
Similar questions
- LRU Cache Supporting O(1) Running Mean
- In-Memory Document Search with Phrase and Boolean Queries
- Linux Process Execution, Filesystem Internals, and Container Isolation
- Variadic Functions and Typesafe Structured Logging
- Backward Chunked Reader for Trailing File Lines
- Distinct Ledger Subsets Summing to a Target Balance
More Confluent interview questions
- Resolve Calls Against Fixed and Variadic Signatures Medium
- Validate Consistency of a Partial 9x9 Sudoku Grid Medium
- Verify and Lexicographically Solve a 9x9 Sudoku Grid Medium Pro
- Backward Chunked Reader for Trailing File Lines Medium Pro
- News Aggregator and Disposable Inbox Platform Medium Pro
- Scalable Podcast Ingestion and Subscriber Feed Medium Pro
- LRU Cache Supporting O(1) Running Mean Medium Pro
- In-Memory Document Search with Phrase and Boolean Queries Medium Pro
- Linux Process Execution, Filesystem Internals, and Container Isolation Medium Pro
- Variadic Functions and Typesafe Structured Logging Hard Pro