Trail Guide Snippets

Easysliding windowAlso known as Overlapping Text Chunking

A hiking club is loading its trail guide into a question-answering assistant. The guide is cut into short snippets, and only the few that best match a question go to the model.

Cut cleanly every 50 words and "after the bridge, turn left at the cairn" can land in two snippets, neither of which makes sense alone. So each snippet repeats the last few words of the one before it. Retrieval systems prepare documents this way.

Your task

Write makeChunks(text, size, overlap). The words of text are separated by single spaces. Return a list of chunks, each chunk being words joined by single spaces:

  • The first chunk is words 0 to size - 1.
  • Each next chunk starts size - overlap words after the previous one and holds up to size words.
  • Stop after the first chunk that includes the last word. The last chunk may be shorter than size.

If text is the empty string, return an empty list.

makeChunks(text: string, size: int, overlap: int) → string[]

Examples

Example 1
Input
text = "cross the bridge then turn left at the cairn"
size = 4
overlap = 1
Output
["cross the bridge then", "then turn left at", "at the cairn"]
Why

There are 9 words and each chunk starts 4 - 1 = 3 words after the last. Chunks start at words 0, 3 and 6. The chunk starting at word 6 ("at the cairn") already includes the last word, so you stop there.

Example 2
Input
text = "fill water here the next tap is far"
size = 4
overlap = 2
Output
["fill water here the", "here the next tap", "next tap is far"]
Why

8 words, step 2. Chunks start at words 0, 2 and 4. The chunk at 4 ("next tap is far") ends exactly on the last word, so stop. A chunk starting at word 6 ("is far") would only repeat words you already have.

Example 3
Input
text = "steep path"
size = 5
overlap = 2
Output
["steep path"]
Why

Only 2 words, fewer than the chunk size, so the whole text is one chunk.

Constraints

  • 0 ≤ number of words ≤ 10,000
  • 1 ≤ size ≤ 1,000
  • 0 ≤ overlap < size
  • text has no leading, trailing or double spaces.
Start with brute force

The obvious loop, "step while start is less than the number of words", is fast but wrong. It keeps going after a chunk reaches the end, adding small tail chunks already contained in the previous one. Those duplicates waste index space and can crowd out useful snippets.

The other common slip is stepping by size instead of size - overlap, which gives no overlap.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code