← Questions

Maximum sum of a length-k subarray

0
AmazonCodingLast asked Aug 2025

A coding interview question asked in Amazon's coding round, last asked Aug 2025. It tests sliding window and heap.

Given an integer array and a window length k, return the largest sum of any contiguous subarray of exactly k elements. Use a sliding window, explain its time and space, and discuss how you would split the work across threads for a very large array. The second half of the round moves to a heap problem: the median of the last k numbers of a stream.

Part 1: maximum window sum

Unless you agree on a different interface with the interviewer, assume:

  • max_window_sum(nums: list[int], k: int) -> int
max_window_sum([2, 1, 5, 1, 3, 2], 3)  ->  9    # [5, 1, 3]
max_window_sum([-3, -1, -2], 2)        ->  -3   # [-1, -2]; all values negative
max_window_sum([4], 1)                 ->  4

Part 2: sliding-window median

  • window_medians(nums: list[int], k: int) -> list[float] — the median of every window of length k, left to right; for even k, the mean of the two middle values.
window_medians([1, 3, -1, -3, 5, 3, 6, 7], 3)  ->  [1.0, -1.0, -1.0, 3.0, 5.0, 6.0]
window_medians([1, 4, 2, 3], 2)                ->  [2.5, 3.0, 2.5]

Constraints

  • 1 <= k <= len(nums) <= 2 * 10^5; -10^9 <= nums[i] <= 10^9.
  • Part 1 in O(n) time and O(1) space; Part 2 in O(n log k) time and O(k) space.

Clarifying questions

  • Can values be negative, and can sums overflow 32 bits?
  • What if k is larger than the array?
  • For Part 2, is the input a fixed array or a live stream? How should an even-k median be returned?

What a strong answer covers

  • Part 1: sum the first k, then add the entering element and subtract the leaving one; initialize the best with the first window, not 0, so all-negative arrays work.
  • Running it in parallel: split the array into chunks that overlap by k - 1 elements, compute each chunk's best window, take the maximum.
  • Part 2: a max-heap for the lower half and a min-heap for the upper half, kept balanced; lazy deletion with a hash map of pending removals, pruning stale tops before reading the median.
  • Alternatives for Part 2 and their costs: a sorted list with bisect (O(k) insert), an order-statistic tree or two sorted containers (O(log k)).
  • Edge cases: k = 1, k = n, duplicates in the window, even k.

Follow-ups

  • Part 1 for every window length from 1 to n at once, or the maximum sum with length at least k.
  • Part 2 on an unbounded stream with only the last k values kept.
  • The approximate median when k is too large to hold in memory.

Where it's asked

  • Amazon · Coding · Last asked Aug 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

sliding window · heap

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding