Batch Word and In-Order Phrase Lookup Over Text Documents
Data Structure DesignAuto-graded · 19 test casesLast updated
Build an inverted index with token positions to answer whole-word and in-order phrase queries over documents, handling repeated words and punctuation.
You are given a list of text documents. Document ids are their indices in the list (0, 1, 2, ...). You are also given a batch of queries, and you must answer each one against the documents.
Input
documents: a list of strings.operations: a list of strings. Each entry is"word"or"phrase".arguments: a list of lists of strings.arguments[i]holds the arguments foroperations[i]. The query text isarguments[i][0], or the empty string ifarguments[i]is empty.
Output
Return a list with one entry per query, in the same order as operations. Each entry is a list of document ids sorted in ascending order, with no duplicates.
Tokenization
Apply this rule to documents and to query text alike:
- Convert the text to a case-insensitive form with Python's
str.casefold(). - Split it into tokens, where a token is a maximal run of Unicode letters and digits. Every other character, including punctuation, whitespace, hyphens and the underscore
_, is a separator.
For example, "State-of-the-art" becomes ["state", "of", "the", "art"], and "To be, or not to be." becomes ["to", "be", "or", "not", "to", "be"].
Query types
"word": tokenize the query text. If it yields exactly one token, return the ids of the documents whose token list contains that token (a whole-word match, never a substring match). If it yields zero tokens or more than one token, the answer is an empty list.
"phrase": tokenize the query text into t1, t2, ..., tk. A document matches if its token list contains positions p1 < p2 < ... < pk such that the token at pj equals tj for every j. The words must appear in the same order as in the phrase, but other tokens may appear between them, so they need not be adjacent. A repeated word in the phrase must be matched by a different, later occurrence in the document. If the phrase yields no tokens, the answer is an empty list.
Any other operation name: the answer is an empty list.
Constraints
0 <= len(documents) <= 10^4, and the total number of tokens across all documents is at most about10^6.len(operations) == len(arguments), with at most10^4queries.- Documents and queries may contain arbitrary Unicode text, including empty strings.
- Documents are fixed for the whole batch, so preparing an index once is allowed and encouraged.
- Each answer list must be in ascending order of document id.
Examples
Example 1
Input: run_text_queries(['The quick brown fox.', 'A QUICK fox jumps.'], ['word', 'phrase'], [['quick'], ['quick fox']])
Output: [[0, 1], [0, 1]]
Example 2
Input: run_text_queries(['To be, or not to be.'], ['word', 'phrase'], [['be'], ['to be or not to be']])
Output: [[0], [0]]
Example 3
Input: run_text_queries(['state-of-the-art systems', 'State of the art design', 'artistic systems'], ['word', 'phrase', 'phrase'], [['art'], ['state art'], ['state of the art']])
Output: [[0, 1], [0, 1], [0, 1]]
Hints
Hint 1
Tokenize once per document and build an inverted index that maps each token to the documents containing it, plus the sorted positions of that token inside each document.
Hint 2
For a phrase, first intersect the document sets of its distinct tokens to get candidates. Then verify each candidate separately.
Hint 3
To verify in-order matching, walk through the phrase and, for each token, find the first occurrence strictly after the previous matched position (binary search over the stored positions). This handles repeated words correctly.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Tokenize every document once with the stated rule (casefold, then maximal runs of letters and digits). While doing so, build two structures:
postings[token]: the ascending list of document ids that contain the token.positions[token][doc_id]: the ascending list of token positions of that token in that document.
Word query. Tokenize the query. If it does not produce exactly one token, return []. Otherwise return a copy of that token's postings list, which is already sorted and duplicate-free.
Phrase query. Tokenize the phrase. If it is empty, return [].
- Narrow candidates: intersect the postings sets of the phrase's distinct tokens. If any token is unknown, the result is empty.
- Verify each candidate in ascending id order. Keep a
currentposition, initially-1. For each phrase token, binary search its position list in that document for the first position strictly greater thancurrent. If none exists, the document fails. Otherwise setcurrentto that position and continue. If every token is placed, the document matches.
Why it is correct
Choosing the earliest possible position for each phrase word leaves the most room for later words, so a greedy left-to-right choice finds an in-order placement exactly when one exists. The strict inequality means a repeated word, as in "to be or not to be", must use a later occurrence, so one occurrence is never counted twice. Candidate filtering only removes documents that lack some phrase word, and those can never match. Because documents are visited in ascending order and postings are built in document order, outputs are sorted with no duplicates. Unknown operations, empty queries and multi-token word queries return [] as specified.
Complexity
- Build:
O(T)time and space, whereTis the total number of tokens, plus the cost of tokenizing the text. - Word query:
O(r)to copyrresults. - Phrase query:
O(sum of postings sizes of the phrase's distinct tokens)to intersect, plusO(c * k * log m)to verifyccandidates withkphrase tokens and at mostmoccurrences per token in a document.
Reference solution
import re
from bisect import bisect_right
from collections import defaultdict
from typing import List
def run_text_queries(documents: List[str], operations: List[str], arguments: List[List[str]]) -> List[List[int]]:
token_pattern = re.compile(r"[^\W_]+", re.UNICODE)
def tokenize(text):
return token_pattern.findall(text.casefold())
# token -> list of doc ids (ascending); token -> doc id -> sorted positions
postings = defaultdict(list)
positions = defaultdict(lambda: defaultdict(list))
for doc_id, document in enumerate(documents):
for position, token in enumerate(tokenize(document)):
if not positions[token][doc_id]:
postings[token].append(doc_id)
positions[token][doc_id].append(position)
def find_word(word):
tokens = tokenize(word)
if len(tokens) != 1:
return []
return list(postings.get(tokens[0], []))
def find_phrase(phrase):
tokens = tokenize(phrase)
if not tokens:
return []
candidate_sets = [set(postings.get(token, [])) for token in set(tokens)]
if any(not c for c in candidate_sets):
return []
candidates = set.intersection(*candidate_sets)
matches = []
for doc_id in sorted(candidates):
current = -1
ok = True
for token in tokens:
occ = positions[token][doc_id]
idx = bisect_right(occ, current)
if idx == len(occ):
ok = False
break
current = occ[idx]
if ok:
matches.append(doc_id)
return matches
results = []
for operation, args in zip(operations, arguments):
query = args[0] if args else ""
if operation == "word":
results.append(find_word(query))
elif operation == "phrase":
results.append(find_phrase(query))
else:
results.append([])
return results