KatInterview

Exact-Phrase Lookup Across a Document Collection

Data Structure DesignAuto-graded · 18 test cases
HardAuto-gradedData Structure Designinverted-indexstring-searchhashing

Last 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 000
  • 0 ≤ len(phrases) ≤ 10 000
  • Each passage contains at most 1 000 words.
  • Each phrase contains at most 20 words.
  • 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.