PIXELBANKv9.1.0
Menu

Chunk Text into Overlapping Windows

Problem Statement

Split a long token stream into fixed-size chunks with a fixed overlap, the standard preprocessing for populating a vector memory.

Background

Given n tokens, a chunk size size, and an overlap, chunks start at *0, size-overlap, 2(size-overlap), ...**. Each chunk spans [start, min(start+size, n)). Generation stops once a chunk reaches the end. The step size - overlap must be positive.

Your Task

Implement:

def chunk_ranges(n, size, overlap):

Return a list of (start, end) tuples (end exclusive) covering the stream, with the given overlap. Stop after the chunk that reaches n.

Input Format

  • n (int) total tokens, size (int), overlap (int) with 0 <= overlap < size.

Output Format

  • A list of (start, end) int tuples.

Sample

print(chunk_ranges(10, 4, 1))

Output:

[(0, 4), (3, 7), (6, 10)]

Example:

Input:
print(chunk_ranges(10, 4, 1))
Output:
[(0, 4), (3, 7), (6, 10)]
Reasoning:
  • Compute the stride between chunk starts using the formula step=size−overlapstep = size - overlap, which yields 4−1=34 - 1 = 3; this determines how far the window shifts after each chunk.
  • Initialize the first chunk at index 0; its end is calculated as min⁡(0+4,10)=4\min(0 + 4, 10) = 4, producing the range (0,4)(0, 4) since it has not yet reached the total length n=10n=10.
  • Advance the start position by the stride to 0+3=30 + 3 = 3; the new end is min⁡(3+4,10)=7\min(3 + 4, 10) = 7, creating the overlapping range (3,7)(3, 7) where the overlap of 1 token is shared with the previous chunk.
  • Advance the start position again by the stride to 3+3=63 + 3 = 6; the new end is min⁡(6+4,10)=10\min(6 + 4, 10) = 10, creating the range (6,10)(6, 10).
  • Since the end index 1010 equals the total token count nn, the generation stops, and the final output is [(0, 4), (3, 7), (6, 10)].

Constraints:

  • 0 <= overlap < size, size >= 1, n >= 0.
  • Step is size - overlap; each chunk is [start, min(start+size, n)).
  • Stop once a chunk's end reaches n; if n == 0 return [].
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Chunk Text into Overlapping Windows - Medium | PixelBank