Exact-Phrase Lookup Across a Document Collection
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests building a positional inverted index so that multi-word phrases can be found by exact word sequence across many documents with repeated queries handled efficiently.
Problem
You are given a collection of text passages and a list of search phrases. For each phrase, return the indices of every passage that contains that phrase as an exact, contiguous sequence of words — same words, same order, no gaps.
Word boundaries are defined by whitespace. Two or more spaces between words behave the same as one.
Function Signature
def find_phrase_matches(passages: List[str], phrases: List[str]) -> List[List[int]]:
Parameters
passages— a list of strings. Each string is a space-separated sequence of lowercase alphanumeric words.phrases— a list of query strings in the same format.
Return value
A list of the same length as phrases. The i-th element is a sorted list of passage indices (0-based) where phrases[i] appears as a contiguous word sequence. If no passage matches, return an empty list for that entry.
Constraints
1 ≤ len(passages) ≤ 10 0000 ≤ len(phrases) ≤ 10 000- Each passage contains at most
1 000words. - Each phrase contains at most
20words. - All characters are lowercase ASCII letters, digits, or spaces.
- An empty or whitespace-only phrase matches no passage and returns
[]. - A passage that contains the phrase multiple times is listed once.
- Passage indices in each result list must appear in ascending order.
- The same phrase may appear multiple times in
phrases; your solution must handle repeated queries efficiently.
Examples
Example 1
Input: find_phrase_matches(['the quick brown fox', 'the brown fox jumps'], ['brown fox'])
Output: [[0, 1]]
Example 2
Input: find_phrase_matches(['one two three', 'one two', 'two three'], ['one two', 'two three', 'three two'])
Output: [[0, 1], [0, 2], []]
Hints
Hint 1
A word-level inverted index (word → documents) can tell you which passages share all the words in a phrase, but it cannot rule out cases like 'fox brown' matching a passage that has both words in the wrong order. To verify ordering, you also need to record *where* each word sits inside each passage.
Hint 2
Once you store word positions, phrase matching becomes an offset check: if word 0 of the phrase starts at position s, then word i must appear at position s + i in the same passage. Anchor your search on the first word of the phrase and test every candidate start position.
Hint 3
Building the index once and caching each query's result pays off when the same phrase is asked many times. Return a copy of the cached list so that any mutation by the caller doesn't corrupt your cache.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why a plain word index isn't enough
A standard inverted index maps each word to the set of passages containing it. Intersecting those sets for all words in a phrase finds passages that contain every word, but says nothing about whether those words appear consecutively and in the right order. A passage containing "fox" and "brown" in either order would be a false positive for "brown fox".
Positional inverted index
Extend the index to store where each word appears:
postings[word][passage_id] = {set of integer positions}
Building this is a single linear pass over all tokens, O(T) time and space where T is the total token count.
Phrase matching via offset checks
A phrase w₀ w₁ … wₖ₋₁ matches a passage p starting at position s when:
w₀appears at positionsinp, andwᵢappears at positions + iinpfor everyifrom 1 to k − 1.
The algorithm:
- Look up every passage that contains
w₀(the first phrase word). These are the only candidates. - For each candidate passage, retrieve the position sets for the remaining phrase words.
- For each start position
sofw₀, do O(k) set lookups to verify the offsets. - On the first confirmed match, record the passage and stop checking other start positions for it (so each passage appears at most once).
- Sort the result list to satisfy the ascending-index requirement.
Efficiency for repeated queries
The index is built once. Each unique phrase's result is stored in a cache keyed by the phrase string. A cache hit returns a copy in O(m) time (m = number of matches). This is important when the same phrase is queried thousands of times in a batch.
Why it is correct
Every true match starts at some position of w₀, so the outer loop misses nothing. Every candidate start position is tested against all offsets, so false positives are rejected. The break after the first confirmed match prevents duplicates. Sorting produces ascending order.
Edge-case handling:
- Empty or whitespace-only phrase:
split()returns[], immediately returning[]. - Phrase word never in index:
postings.get(word, {})returns an empty dict, so the outer loop has no iterations and the result is[]. - Multiple spaces in input:
split()with no argument normalises any whitespace run to a single separator. - Phrase occurs multiple times in one passage: the
breakensures the passage is counted once. - Phrase longer than the passage: offset checks fail naturally.
Complexity
Let T = total tokens across all passages, k = phrase length, m = number of matching passages for a given query.
| Operation | Time | Space |
|---|---|---|
| Index build | O(T) | O(T) |
| Single query (uncached) | O(occurrences of w₀ × k + m log m) | O(k) working memory |
| Repeated query (cached) | O(m) | O(m) per cached entry |
Reference Solution
from collections import defaultdict
from typing import List
def find_phrase_matches(passages: List[str], phrases: List[str]) -> List[List[int]]:
# Build positional index: word -> passage_id -> set of positions
postings = defaultdict(lambda: defaultdict(set))
for passage_id, passage in enumerate(passages):
for position, word in enumerate(passage.split()):
postings[word][passage_id].add(position)
results = []
cache = {}
for phrase in phrases:
# Return a copy of a cached result when possible
if phrase in cache:
results.append(cache[phrase][:])
continue
words = phrase.split()
if not words:
cache[phrase] = []
results.append([])
continue
matches = []
# Iterate over passages that contain the first word
for passage_id, start_positions in postings.get(words[0], {}).items():
# Pre-fetch position sets for each subsequent word in this passage
later_positions = [
postings.get(w, {}).get(passage_id, set())
for w in words[1:]
]
# Test every candidate start position
for start in start_positions:
if all(start + offset + 1 in later_positions[offset]
for offset in range(len(later_positions))):
matches.append(passage_id)
break # count each passage at most once
matches.sort()
cache[phrase] = matches
results.append(matches[:])
return results