← All Lessons Lesson 44 / 68
Lesson 44

Finding the Smallest Sum of a Fixed-Size Window in an Array

Smallest Sum Among All Subarrays of Size k

Imagine you have a row of numbers, and you want to look at them through a small window that is exactly k numbers wide. As you slide that window from the left end to the right end, each position shows you a group of k neighbors sitting next to each other. The task is to add up the numbers in each window and find the smallest total you can get.

A subarray is just a chunk of the array made of elements that are next to each other (no gaps, no reordering). A subarray "of size k" simply means a chunk that contains exactly k numbers.

The problem in plain words

You are given:

  • an integer array called arr
  • a positive whole number k

Your job is to look at every possible group of k neighbors, add each group, and return the minimum sum. If the array is too short to even form one group of size k, there is no valid answer, so you return -1.

Walking through Example 1

Input: arr = [4, 4, 5, 6, 4], k = 3

Slide a window of size 3 across the array:

  • [4, 4, 5] → sum is 4 + 4 + 5 = 13
  • [4, 5, 6] → sum is 4 + 5 + 6 = 15
  • [5, 6, 4] → sum is 5 + 6 + 4 = 15

The smallest of these sums is 13, so the output is 13.

Walking through Example 2

Input: arr = [1, 2, 3, 5], k = 1

When k = 1, each window holds just one number. So the windows are [1], [2], [3], [5]. The smallest single number is 1, so the output is 1.

A simple way to think about solving it

The slow idea would be: for every starting position, add up the next k numbers from scratch. That works, but it repeats a lot of addition.

A smarter trick is the sliding window. Notice that when the window moves one step to the right, it only loses one number on the left and gains one number on the right. So instead of re-adding everything, you can:

  1. Add the first k numbers to get the first window sum. Call this your current sum and also your best (minimum) sum so far.
  2. Move the window one step at a time. Each step, add the new number entering on the right and subtract the old number leaving on the left.
  3. After each move, check if this new sum is smaller than your best sum. If it is, update the best sum.
  4. When the window reaches the end, the best sum you kept is the answer.

Don't forget the edge case

If k is larger than the number of elements in arr, you can never build a window of size k. In that case, return -1.

Finding the Smallest Sum of a Fixed-Size Window in an Array
Diagram — click to zoom (scroll / drag to pan)