Sliding Window Average After Dropping the Largest Values
GoogleSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to maintain order and perform efficient removals within a sliding window using balanced data structures or heaps.
Problem Statement
Given an array of integers nums, a window size w, and an integer k, compute the average of the elements in each sliding window of size w after removing the k largest values.
If the window contains duplicates, treat each occurrence as a distinct value to be removed. If k is 0, return the average of all elements in the window. The result for each window should be the sum of the remaining w - k elements divided by (w - k).
Function Signature
def sliding_window_average(nums: List[int], w: int, k: int) -> List[float]:
Constraints
1 <= w <= len(nums) <= 200,0000 <= k < w-10^6 <= nums[i] <= 10^6
Example
Input: nums = [1, 5, 2, 8, 3], w = 3, k = 1
- Window
[1, 5, 2]: Largest is 5. Remaining:[1, 2]. Average:1.5 - Window
[5, 2, 8]: Largest is 8. Remaining:[5, 2]. Average:3.5 - Window
[2, 8, 3]: Largest is 8. Remaining:[2, 3]. Average:2.5Output:[1.5, 3.5, 2.5]
Edge Cases
k = 0(Simple sliding window sum)k = w - 1(Only the smallest element remains)- All elements in the window are identical.
Hints
Hint 1
To efficiently track the largest elements in a sliding window, consider using two balanced data structures (like multisets or two heaps) to separate the smallest `w-k` elements from the largest `k` elements.
Hint 2
A sliding window approach requires adding the new element and removing the old one; ensure your data structures support logarithmic time insertion and deletion.
Hint 3
Maintain the sum of the 'smallest' subset separately to avoid recalculating the average from scratch at every step.
Follow-up questions
- How would your approach change if the window size `w` could be very large compared to the number of removals `k`?
- If the input stream was massive and arrived in real-time, how would you modify your solution to minimize memory usage?
- What is the time complexity of your solution, and can it be optimized using a specialized data structure like a Fenwick tree or Segment tree if values were discretized?
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.