07Sliding windowArrays and hashing

Sliding window, fixed size

Numbers next to each other and a fixed length k: one number in, one out, reuse the previous sum.

One Hint Away (@onehintaway). Clues: numbers next to each other (a subarray or substring) and a fixed length k.

Worked example: the biggest sum of k numbers in a row, the GeeksforGeeks problem "Max Sum Subarray of size K".

The walk

nums = [2, 1, 5, 1, 3, 2], k = 3 returns 9.

windowinoutsum
[2, 1, 5]first window8
[1, 5, 1]127
[5, 1, 3]319
[1, 3, 2]256

Who leaves? When nums[i] joins, nums[i - k] leaves. At i = 3, index 3 - 3 = 0 drops out, so the window stays exactly k long.

Pseudocode

Pseudocode · any language
function maxSum(nums, k):
    total = 0
    for i from 0 to k - 1:
        total = total + nums[i]
    best = total
    for i from k to length(nums) - 1:
        total = total + nums[i] - nums[i - k]
        best = max(best, total)
    return best

The trap: taking away the wrong number. Subtract nums[i - k + 1] by mistake and at i = 3 you remove the 1 that is still inside the window. The sums come out 8, 8, 6, 7 and you return 8 instead of 9. The number that leaves is always nums[i - k].

Code

class Solution {
    // O(n) time, O(1) space
    public int maxSum(int[] nums, int k) {
        int total = 0;
        for (int i = 0; i < k; i++) {
            total = total + nums[i];
        }
        int best = total;
        for (int i = k; i < nums.length; i++) {
            total = total + nums[i] - nums[i - k];
            best = Math.max(best, total);
        }
        return best;
    }
}

If a platform allows very large numbers or very long arrays, the sum can pass the 32-bit limit (about 2.1 × 10^9). Use long in Java and long long in C++ there.

Complexity

VersionTimeExtra space
Re-add every windowO(n·k)O(1)
Sliding windowO(n)O(1)

How it was tested

Verified: all four languages return 9 on the example, the wrong-index version returns 8, and the code matches a re-add-every-window version on 3,000 random inputs, including negative numbers. Re-run on 31 October 2026 on 3,001 inputs (3,000 random arrays of length 1 to 12 with values from −50 to 50 and every valid k, plus the example): all four languages matched on every one.

Practice

Try these in order. Open the worked example first if you got stuck on the slides.