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.
The problem
Given a list of integers and a window size k, return the largest sum of any k consecutive elements.
[5, 1, 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).
Step-by-step approach
- Compute the sum of the first
kelements; that is the current and best sum. - For each
ifromkton - 1: addnums[i]and subtractnums[i - k]. - Update the best sum.
- Return the best (decide in advance what to return when
k > n).
Python solution
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 bestComplexity
The first window costs O(k) and each later window costs O(1), so the total is O(n).
Common mistakes
- Initialising
best = 0, which is wrong when every window sum is negative. - An off-by-one in the element that leaves: it is
nums[i - k], notnums[i - k + 1]. - Not handling
k > len(nums), which makessum(nums[:k])silently sum a shorter list.
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.