Word and Phrase Lookup in a File Too Big to Load
System DesignModel answerLast updated
Design an API to find every line containing a word or exact phrase in a large line-oriented text file, comparing a streaming scan against a persistent inverted index.
Word and Phrase Lookup in a File Too Big to Load
You are given a text file where each line holds exactly one sentence. The file can be arbitrarily large — assume it does not fit in memory. Your task is to design an API that locates every line containing a target word, then extend that design to support exact multiword phrase search.
Address two scenarios:
- One-off query: a user runs a single search and moves on.
- Repeated queries: the file is mostly stable and the same system will answer many searches over time.
For each scenario, describe the algorithm, data structures, result format, and resource profile.
Expected coverage
- How you tokenize text (case folding, punctuation, Unicode).
- What "exact phrase" means and how you enforce word adjacency within a line.
- How results are reported (line number, byte offset, or both).
- How you handle file updates (appends, rewrites) and keep results consistent.
- Trade-offs between the two approaches in terms of latency, memory, disk, and build time.
Constraints and assumptions
- You may stream the file sequentially; you may not load it fully into RAM.
- Results must identify the line number at minimum; byte offsets are a bonus.
- You must explicitly state your tokenization rules, including punctuation and Unicode behavior.
- The repeated-query design may write auxiliary data to disk.
- Phrase terms must appear adjacent and in order within a single line (no cross-line matches).
Clarifying questions worth raising
- Should a word match only on token boundaries, or is substring matching acceptable?
- Is the query workload sparse enough that scan latency is tolerable, or is sub-second response required?
- Is the file append-only, or can arbitrary lines be modified or deleted?
- What character encoding should be assumed? UTF-8 with possible BOM?
Hints
Hint 1
For a one-off scan, you only need to hold one line in memory at a time. Think about what the minimum state is to check whether a line contains the target word or phrase after tokenizing it.
Hint 2
For repeated queries, an inverted index maps each token to the list of lines where it appears. Phrase search needs more than just line membership — you also need to know the position of each token within the line so you can verify adjacency.
Hint 3
File updates are the tricky part of the persistent index. Think about what happens if lines shift after an append, and how you can detect that the index is stale relative to the file it was built from.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem has two distinct modes. Treat them separately, then compare.
Tokenization (applies to both modes)
Pick a consistent tokenization scheme and apply it identically at index time and query time — inconsistency here is the most common source of missed matches.
Recommended rules:
- Lowercase everything (Unicode case-fold, not just ASCII
tolower). - Split on whitespace and strip leading/trailing punctuation from each token (
"fast,"→"fast"). - Preserve internal apostrophes and hyphens as part of the token (
"it's","state-of-the-art") unless the domain calls for splitting them. - Normalize Unicode to NFC before any comparison.
- Skip empty tokens produced by consecutive delimiters.
A phrase query must also be tokenized the same way before lookup. If the query is "Fast, reliable", it becomes ["fast", "reliable"].
Mode 1: One-Off Streaming Scan
Word search — read the file line by line, tokenize each line, check whether the target token appears in the token set (a set or a simple membership scan for short lines). Emit (line_number, line_text) for every match. Memory at any moment: one line buffer plus the query token. Time: O(N) where N is total characters. No preprocessing.
Phrase search — tokenize each line into an ordered list. Then check whether the phrase token sequence appears as a contiguous subsequence. A sliding window or a simple scan works:
def contains_phrase(line_tokens: list[str], phrase_tokens: list[str]) -> bool:
p = len(phrase_tokens)
return any(
line_tokens[i:i+p] == phrase_tokens
for i in range(len(line_tokens) - p + 1)
)
This is O(L × P) per line where L is tokens in the line and P is tokens in the phrase. For typical sentence lengths this is negligible.
Result format: {"line_number": 142, "byte_offset": 8821, "text": "..."}. Track byte offset with a counter as you read; for UTF-8 use file.tell() before each readline().
When to use it: infrequent queries, scripts, or when the file changes often enough that building an index is not worth it.
Mode 2: Persistent Positional Inverted Index
Build this once, serialize to disk, and reuse for many queries.
Index structure:
token → [(line_number, position_in_line), ...]
Position is the zero-based index of the token within its line's token list.
Build pass — one sequential read:
index = defaultdict(list)
with open(path, "rb") as f:
line_num = 0
for raw_line in f:
tokens = tokenize(raw_line.decode("utf-8"))
for pos, token in enumerate(tokens):
index[token].append((line_num, pos))
line_num += 1
Memory during build: the full index, which is typically 2–5× the raw text size depending on vocabulary. If that is still too large, build a disk-based structure (B-tree, sorted SSTable) in chunks.
Phrase lookup:
- Fetch the postings list for each phrase token.
- Start with the postings for
phrase[0]. For each(line, pos)entry, check whether(line, pos+1)exists inphrase[1]'s postings,(line, pos+2)inphrase[2]'s, and so on. - Intersect using sorted merge (postings are naturally sorted by line then position during a sequential build).
Time per query: O(k × |postings|) where k is phrase length. For rare words the postings list is short; for common words it can be large, so query the rarest term first.
Serialization: a simple format is one file of sorted (token, line, pos) triples plus a separate token-to-offset lookup. A SQLite table with an index on token works well for a prototype and handles partial updates.
File Updates and Version Binding
This is where most candidates lose points.
- Store a file fingerprint (mtime + byte length, or a rolling checksum of the first N bytes) alongside the index.
- On every query, compare the live file's fingerprint to the stored one. A mismatch means the index is stale — either reject the query or fall back to the streaming scan while rebuilding.
- Append-only files are easiest: existing line numbers do not shift. Index only the new bytes from the last known offset and merge into the existing index.
- In-place edits (line deletions or replacements) invalidate line-number semantics entirely. The safest response is a full rebuild. If rebuilds are expensive, assign stable line IDs and store a side file that maps line ID to current byte offset — but this is significant added complexity.
Trade-Off Summary
| Dimension | Streaming scan | Inverted index |
|---|---|---|
| Query latency | O(file size) | O(postings size) |
| Memory | O(1) | O(index size) |
| Disk | None | 2–5× file size |
| Build cost | None | One full sequential pass |
| Handles updates | Always correct | Requires staleness check |
| Phrase support | Trivial | Needs positional postings |
Common Mistakes
- Tokenizing differently at build vs. query time — the single most frequent bug.
- Storing only line membership (no positions) and then being unable to verify phrase adjacency.
- Assuming ASCII —
tolower()breaks on accented characters; use Unicode case-folding. - Ignoring file version binding — returning stale results without warning is worse than returning an error.
- Loading all postings into memory at once for a large common word — stream and merge instead.