InterviewPrepKit

Home / Coding / Agent Coding / Retrieval (RAG) / Chunk Text with Overlap

Chunk Text with Overlap

medium 00:00
Solving tips
  • Chunking is the first stage of every RAG pipeline: bad chunks cap retrieval quality no matter how good the embedder is.
  • The overlap keeps context that straddles a chunk boundary from being lost, but it also creates the classic infinite-loop trap.
  • Guard the step size: if overlap >= chunk_size the window never advances, so clamp it and always move forward by at least one word.

Before a document can be retrieved by a RAG system it has to be split into chunks small enough to embed and to fit an LLM’s context window. Naive splitting drops context that spans a boundary, so production chunkers repeat a few words between neighbors. Your job is to build that chunker.

How chunking with overlap works

Treat the text as a list of whitespace-separated words. Slide a window of chunk_size words across the list. After emitting a chunk, advance the window by chunk_size - overlap words, so the next chunk starts by repeating the last overlap words of the previous one. Repeat until every word has been covered.

The trap: if overlap is greater than or equal to chunk_size, the step chunk_size - overlap is zero or negative and the window never moves forward, looping forever. You must prevent that.

Task

Complete chunk_text(text, chunk_size, overlap=0):

  1. Split text into words on whitespace. If there are no words, return [].
  2. Emit chunks of at most chunk_size words, joined back into strings with single spaces.
  3. Between consecutive chunks, share overlap words. Clamp overlap so the window always advances by at least one word (never allow an infinite loop).
  4. If the text has fewer than chunk_size words, return a single chunk containing all of it.

Example

text = "one two three four five six seven"
chunk_text(text, chunk_size=3, overlap=1)
# -> ["one two three", "three four five", "five six seven", "seven"]

chunk_text("short text", chunk_size=10, overlap=2)
# -> ["short text"]

Constraints

  • chunk_size >= 1. Assume the caller passes a positive chunk_size.
  • overlap may be passed as any non-negative int; clamp it internally so chunk_size - overlap >= 1.
  • Split and join on single spaces; you do not need to preserve the original whitespace runs.
  • No external libraries beyond the standard library and typing.

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