Code Lab / Challenge 9

Text Chunking Strategies

EasyFixed, sliding-window, recursive, sentence chunkers

The problem, as an interviewer would set it

Implement four chunkers used in RAG ingestion pipelines:

    chunk_fixed(text, size) -> list[str]
        Non-overlapping fixed-size chunks. Concatenating the chunks must
        reconstruct the original text exactly.

    chunk_sliding(text, size, overlap) -> list[str]
        Sliding window: each chunk is at most `size` chars and consecutive
        chunks share exactly `overlap` chars (step = size - overlap).
        Every character of the text must be covered. overlap < size required.

    chunk_sentences(text, max_size) -> list[str]
        Split into sentences (on ., !, ? followed by whitespace), then greedily
        pack whole sentences into chunks of at most `max_size` chars. A single
        sentence longer than max_size is hard-split so the invariant holds.

    chunk_recursive(text, max_size, separators=("\n\n", "\n", ". ", "")) -> list[str]
        Recursive splitter (LangChain-style): try the coarsest separator first;
        pieces still over max_size fall through to finer separators, ending
        with a raw character split. Separators stay attached to the preceding
        piece so that "".join(chunks) == text.

All chunkers must return only non-empty chunks and respect their size bound.
What interviewers look for

Overlap handling, boundary preservation, no dropped/duplicated text at edges

A strong solution demonstrates:
- Treating chunker properties as invariants (coverage, max size, overlap)
  and testing the invariants rather than hard-coding expected chunk lists.
- Correct sliding-window arithmetic: step = size - overlap, and the guard
  overlap < size (step <= 0 loops forever - a classic bug).
- In the recursive splitter, keeping separators attached so no characters are
  silently dropped; naive str.split() loses them and corrupts offsets.
- Knowing WHY each strategy exists: fixed is simple but cuts mid-sentence;
  overlap protects boundary context at the cost of index bloat (size 512 /
  overlap 128 stores ~1.33x the text); sentence/recursive respect semantics.
Common mistakes: dropping the tail chunk, empty-string chunks, off-by-one at
the last window, and recursion that never terminates on separator-free text.
Follow-ups: return (chunk, start_offset) pairs for citation highlighting;
token-based sizes with a real tokenizer (embedding models cap input in
tokens, not characters); semantic chunking via embedding similarity between
adjacent sentences; contextual chunk headers (prepend the document title or
an LLM-written one-line summary of where the chunk sits before embedding);
small-to-big retrieval (match on small chunks, return the parent section).

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge