Top-K Largest Elements in Every Sliding Window
CitadelSoftware Engineer · Technical ScreenLast updated
Design an algorithm to maintain and extract the top-K largest elements in descending order for each sliding window of size W across an array.
Problem Statement
You are given an integer array nums, an integer w representing the sliding window size, and an integer k. As the window slides from the leftmost position to the rightmost position one element at a time, you need to identify the k largest elements inside the window.
Return a list of lists, where each inner list contains the k largest elements in the corresponding window, sorted in descending order.
Function Interface
def top_k_sliding_window(nums: list[int], w: int, k: int) -> list[list[int]]:
pass
Input and Output Format
- Input:
nums: A list of integers.w: The width of the sliding window.k: The number of largest elements to retrieve per window.
- Output:
- A list of lists of integers with length
len(nums) - w + 1. Each sublist has lengthkand is sorted in descending order.
- A list of lists of integers with length
Examples
Example 1
Input: nums = [4, 1, 3, 2, 6, 5], w = 3, k = 2
Output: [[4, 3], [3, 2], [6, 3], [6, 5]]
Explanation:
- Window [4, 1, 3]: top 2 largest are [4, 3]
- Window [1, 3, 2]: top 2 largest are [3, 2]
- Window [3, 2, 6]: top 2 largest are [6, 3]
- Window [2, 6, 5]: top 2 largest are [6, 5]
Example 2
Input: nums = [10, 10, 10, 2], w = 3, k = 1
Output: [[10], [10]]
Explanation:
- Window [10, 10, 10]: top 1 largest is [10]
- Window [10, 10, 2]: top 1 largest is [10]
Constraints
1 <= nums.length <= 10^51 <= w <= nums.length1 <= k <= min(w, 50)-10^9 <= nums[i] <= 10^9
Edge Cases to Consider
- Duplicate values within the same sliding window.
k == 1(equivalent to the classic sliding window maximum).k == w(all window elements must be sorted and returned).
Hints
Hint 1
A standard binary heap does not support arbitrary removal of elements sliding out of the window in logarithmic time without auxiliary tracking.
Hint 2
Consider maintaining an ordered multiset or self-balancing binary search tree representing the current window so elements can be inserted and deleted in O(log w) time.
Hint 3
If using heaps, you can maintain two heaps (top K and bottom W-K) combined with lazy deletion to handle out-of-window elements.
Follow-up questions
- If we only needed the sum of the top K elements rather than the elements themselves, how could we achieve O(log w) per window shift even when K is large?
- How would you optimize the approach if K is very small (e.g., K = 2) compared to when K is close to W?
- How would your design change if elements arrive out-of-order in a real-time stream with event-time timestamps rather than a continuous array?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.