Heaps and Priority Queues
86 / 170Heaps and Priority QueuesLesson 6 of 8About 52 min
Split the data at the middle and keep both halves' inner edges available. That is the median, maintained.
Any time a problem wants a running statistic from the middle of a stream, this is the shape. Percentiles other than the median work the same way with an uneven split.
It also answers the sliding-window median, with the added difficulty of removing values that have expired, which heaps do not support directly. That variation needs lazy deletion, and knowing that the plain two-heap arrangement does not cover it is worth as much as knowing the arrangement.
Add 5, then 15, then 1 to an empty structure. After each add, give the contents of the lower half as actual values in descending order, the upper half in ascending order, and the median. Write an empty half as [].
| added | lower | upper | median |
|---|---|---|---|
| 5 | |||
| 15 | |||
| 1 |
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.