← Questions
Largest and smallest median over sliding windows
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's online assessment, last asked Jul 2025. It tests sorting and greedy.
You are given an integer array nums and a window length k. Slide a window of k consecutive elements across the array. For every window take its median; when k is even, use the lower of the two middle values. Return the largest and the smallest of these medians.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
median_extremes(nums: list[int], k: int) -> list[int]— returns[max_median, min_median], or[]whenk > len(nums).
The median of a window is its element at sorted index (k - 1) // 2.
Example
nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 -> [6, -1]
# window medians: 1, -1, -1, 3, 5, 6
nums = [4, 1, 3, 2], k = 2 -> [2, 1]
# lower medians of [4, 1], [1, 3], [3, 2]: 1, 1, 2
nums = [5, 2, 8, 1], k = 1 -> [8, 1]
Constraints
-
0 <= len(nums) <= 10^5,-10^9 <= nums[i] <= 10^9 - Aim for O(n log k) time and O(k) extra space.
Clarifying questions
- Are the
kelements consecutive, or anykelements in order? - For even
k: the lower middle, the upper middle or their average? - What to return when
kis larger than the array? - Can values repeat?
What a strong answer covers
- The brute force (sort each window, O(n k log k)) and why it is too slow.
- Keeping the window in an ordered structure so each slide is O(log k): two heaps with lazy deletion, a sorted list with binary-search insert and delete, or a Fenwick tree over compressed values.
- Reading the element at index
(k - 1) // 2after every slide and keeping a running max and min. - Removing the right copy when values repeat; tests with
k = 1,k = nand an evenk.
Follow-ups
- The
kelements no longer need to be consecutive: any subsequence of lengthk. What are the largest and smallest medians now, and why does sorting the array answer it? - Return the sum of all window medians.
- Values arrive as a stream; report the median of the last
kvalues after each one.
Where it's asked
- Amazon · Online assessment · Last asked Jul 2025Coding problems plus a repository bug-fix section with a built-in assistant or a design scenario, then a work-style survey · AI only inside the bug-fix section's built-in assistant
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
