Skip to main content

Write a function that splits a list of tokens into chunks of a fixed size, where each chunk shares some tokens with the one before it. For example, tokens 1 to 10 with size 4 and overlap 1 should give 1 to 4, 4 to 7 and 7 to 10.

Coding rounds · Intermediate 2

Short answer

Move a window of the chunk size forward by step = size - overlap, taking tokens[start:start + size] each time. Stop once a window reaches the end of the text, so the last chunk is not repeated. Reject an overlap that is not smaller than the size. Cost is O(n), plus the repeated overlap tokens.

Deeper answer

Clarify first: is the size counted in characters, words or model tokens? Token counts match the limit of the embedding model best. Ask whether chunks may cut through a sentence, and what metadata each chunk needs, such as the source document and the start position.

The core is a loop: step = size - overlap, then for start in range(0, n, step), append tokens[start:start + size] and stop as soon as start + size >= n. Without it, the loop can add a final chunk that is fully contained in the previous one. Validate the input: size must be positive and overlap must be at least 0 and less than size, or the step is zero or negative and the loop never moves forward.

Test an empty input, a text shorter than one chunk, a text that divides exactly, and one with a short last chunk. Interviewers watch for the infinite loop, for a dropped last chunk, and for losing the link back to the source.

What a strong answer covers

Answer it out loud in the mock interview about 2.5 min

Follow-ups to expect

Common mistakes

Learn it

Chunk documents for retrieval

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.