Solve sliding-window and heap problems
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates algorithm design and data structure proficiency, focusing on sliding-window techniques for fixed-length subarray aggregates and heap- or hashmap-based approaches for maintaining medians in a real-time integer stream, along with considerations for concurrent execution.
Constraints
- 1 <= len(nums) <= 200000
- 1 <= k <= len(nums)
- -10^9 <= nums[i] <= 10^9
- Return medians as floats; for even k, use (a + b) / 2.0 with no rounding beyond floating-point defaults
- Target time complexity: O(n log k), space: O(k)
Hints
- Maintain two heaps: a max-heap for the lower half and a min-heap for the upper half of the window.
- Balance heaps so that the max-heap has either the same number of valid elements as the min-heap or one more.
- Use a hashmap for lazy deletion to remove elements that slide out without direct heap deletion.
- When computing the median, prune invalid (delayed) elements from heap tops.
- For even k, average the max of the lower half and the min of the upper half.