KatInterview

Word and Phrase Lookup in a File Too Big to Load

System DesignModel answer
MediumModel answerSystem Designinverted-indextext-searchstreaming

Last 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.