Coding interview problems › Sliding Window

🪟 Sliding Window Easy

Maximum Sum Subarray of Size K

Maximum Sum Subarray of Size K explained: the fixed sliding window adds the element entering and drops the one leaving: O(n), not O(n·k). Tested Python.

Also searched as: sliding window maximum sum of k consecutive elements · max sum of subarray of size k

🪟

Try it live Free

Sliding Window

This is the lab's core example: slide a window of k elements across the array and watch the sum update by one add and one subtract per step. Compare the work counter with the O(n·k) rescan.

Open the playground →

The problem

Given a list of integers and a window size k, return the largest sum of any k consecutive elements.

Inputnums = [2, 1, 5, 1, 3, 2], k = 3
Output9

[5, 1, 3].

Inputnums = [-1, -2, -3], k = 2
Output-3

The key insight

Two neighbouring windows share k - 1 elements. Instead of re-adding all k, take the previous window's sum, add the element that enters on the right and subtract the element that leaves on the left. Each window then costs O(1).

Brute force first: Summing each window from scratch costs O(k) per window, O(n·k) in total.

Step-by-step approach

  1. Compute the sum of the first k elements; that is the current and best sum.
  2. For each i from k to n - 1: add nums[i] and subtract nums[i - k].
  3. Update the best sum.
  4. Return the best (decide in advance what to return when k > n).

Python solution

PYTHON 3tested
def max_sum_k(nums, k):
    if k <= 0 or k > len(nums):
        return None                # no window of size k exists
    cur = sum(nums[:k])
    best = cur
    for i in range(k, len(nums)):
        cur += nums[i] - nums[i - k]   # add entering, drop leaving
        best = max(best, cur)
    return best

Complexity

TimeO(n)
SpaceO(1)

The first window costs O(k) and each later window costs O(1), so the total is O(n).

Common mistakes

Frequently asked questions

What is the time and space complexity of the fixed sliding window?

O(n) time and O(1) space. Recomputing each window from scratch is O(n·k).

Does the sliding window work with negative numbers here?

Yes. For a fixed window size you always add one element and remove one, so the sign of the numbers does not matter.

How do I find the maximum element in each window instead of the sum?

Use a monotonic deque of indices, which gives every window's maximum in O(n) total. That is the Sliding Window Maximum problem.

Preparing for placements?

Take the 2-minute readiness check to find your weak patterns, then follow the placement path from DSA core to system design.

All coding interview problems More Sliding Window Sliding Window lab Placement prep guides

Problem statements on this site are written in our own words. Problem names are the common names used across interview-prep communities; BitBootcamp is an independent learning platform and is not affiliated with LeetCode or any company that asks these questions.