← IXL Learning Interview Insights
The two-heap approach is the clean solution here and I knew it going in, one max-heap for the lower half and one min-heap for the upper half.
Use two heaps: a max-heap for the lower half and a min-heap for the upper half, keeping their sizes balanced. After each insertion, the median is either the top of the max-heap (if odd count) or the average of both tops (if even count).
Pro tip: Mention that this approach gives O(log n) insertion and O(1) median retrieval, and discuss how you would handle edge cases like empty stream or duplicate values.
Confirm that the data structure should support addNum(int num) and findMedian() operations, and that the median is defined as the middle value for odd count or average of two middle values for even count.
Select a max-heap to store the smaller half of numbers and a min-heap for the larger half. This allows efficient access to the middle elements.
Maintain the invariant that the max-heap size is either equal to or one greater than the min-heap size. After each insertion, rebalance by moving the top element from the larger heap to the other.
Add the new number to the appropriate heap: if it's less than or equal to the max-heap top, add to max-heap; otherwise, add to min-heap. Then rebalance the heaps.
If total count is odd, return the top of the max-heap. If even, return the average of the tops of both heaps.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.