Neural Mastery
← Practice
Fixed-Size Chunking With Overlapeasy

Fixed-Size Chunking With Overlap

easy RAG & Retrieval 15 min

NumPy allowed · plain Python earns 10 bonus points

RAG step 1/4

A query retrieves context

Embedding similarity ranks the documents before generation.
Open lesson →
01query
02embed
03retrieve
04context
What is RAG?→ embed →top context
retrieval.md44%
rag-systems.md33%
agents.md24%

Cosine-like similarity scores ranked before context assembly

Implement fixed-size character chunking with overlap, the baseline chunking strategy every RAG ingestion pipeline starts from.

Task

Implement chunk_with_overlap(text, chunk_size, overlap). Return chunks of chunk_size characters, advancing the start position by chunk_size - overlap each step, until the whole text is covered. The last chunk may be shorter.

Function Signature

chunk_with_overlap(text: str, chunk_size: int, overlap: int) -> list[str]

Examples

Example 1: basic overlap
Input: text = 'abcdefghij' chunk_size = 4 overlap = 1
Output: ['abcd', 'defg', 'ghij', 'j']
Example 2: no overlap
Input: text = 'abcdef' chunk_size = 2 overlap = 0
Output: ['ab', 'cd', 'ef']
Example 3: text shorter than chunk
Input: text = 'hi' chunk_size = 10 overlap = 2
Output: ['hi']

Constraints

  • 0 <= overlap < chunk_size
  • chunk_size > 0
Python3Saved ✓
def chunk_with_overlap(text, chunk_size, overlap):
# Your implementation here
pass

Case 1: basic overlap
Input: text = 'abcdefghij' chunk_size = 4 overlap = 1
Expected: ['abcd', 'defg', 'ghij', 'j']
Case 2: no overlap
Input: text = 'abcdef' chunk_size = 2 overlap = 0
Expected: ['ab', 'cd', 'ef']
Case 3: text shorter than chunk
Input: text = 'hi' chunk_size = 10 overlap = 2
Expected: ['hi']