InterviewPrepKit

Home / Coding / Agent Coding / Retrieval (RAG) / Deduplicating Retrieved Chunks

Deduplicating Retrieved Chunks

easy 00:00
Solving tips
  • Normalize before you compare: lowercase and collapse whitespace so cosmetic differences don't hide duplicates.
  • A set of seen keys plus a single pass keeps the highest-ranked copy and preserves order.
  • Normalize for the comparison key only; keep the original chunk text in the output.

A retriever often returns the same passage more than once — the same sentence indexed under slightly different casing or spacing, or a chunk that overlaps a neighbor. Feeding those duplicates into the prompt wastes context budget and biases the model toward whatever got repeated. Before the chunks reach the LLM, you dedup them while keeping the best-ranked copy of each.

Task

Implement dedup_chunks(chunks):

  1. Compute a normalized key for each chunk: lowercase it, then collapse every run of whitespace (spaces, tabs, newlines) into a single space and strip the ends.
  2. Walk the list in order. The first time a normalized key is seen, keep that chunk; every later chunk with an already-seen key is dropped.
  3. Return the kept chunks as their original (un-normalized) strings, in the original order.

Because the input is ranked best-first, keeping the first occurrence keeps the highest-ranked copy.

Example

chunks = [
    "The Fed raised rates.",
    "the   fed raised rates.",     # duplicate of #1 after normalization
    "Inflation cooled in Q2.",
    "The Fed raised rates.",       # exact duplicate of #1
]

dedup_chunks(chunks)
# -> ["The Fed raised rates.", "Inflation cooled in Q2."]

Constraints

  • Do not call any real LLM, network, or external service — this is pure string processing.
  • Normalization affects only the comparison key; the returned strings must be the original chunk text.
  • Preserve the input order of the surviving chunks.
  • An empty input returns an empty list.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug