Problem · Array

Sliding-Window Text Chunking

Learn this problem
EasySAP logoSAPINTERNONSITE INTERVIEW

Problem statement

You are given an array of words words, a positive integer chunkSize, and an integer overlap satisfying 0 <= overlap < chunkSize.

Starting at index 0, create a chunk containing up to chunkSize consecutive words. Then advance the start index by chunkSize - overlap and repeat while the start index is within the array.

Return all chunks in source order. Keep the final non-empty chunk even if it contains fewer than chunkSize words. If words is empty, return an empty array.

Function

chunkText(words: String[], chunkSize: int, overlap: int) → String[][]

Examples

Example 1

words = ["a","b","c","d","e"]chunkSize = 3overlap = 1return = [["a","b","c"],["c","d","e"],["e"]]

The window starts at indices 0, 2, and 4. Consecutive chunks overlap by one word.

Example 2

words = ["one","two","three","four"]chunkSize = 2overlap = 0return = [["one","two"],["three","four"]]

With zero overlap, each window begins immediately after the previous one.

Example 3

words = []chunkSize = 4overlap = 1return = []

There are no words, so no chunks are emitted.

Constraints

  • 0 <= words.length <= 10^5
  • 1 <= chunkSize <= 10^5
  • 0 <= overlap < chunkSize
  • Each word is a non-null string.
drafts saved locally
public String[][] chunkText(String[] words, int chunkSize, int overlap) {
    // write your code here
}
words["a","b","c","d","e"]
chunkSize3
overlap1
expected[["a", "b", "c", "c", "d", "e", "e"]]
checking account