Priority Queues Medium
Median Maintenance with Two Heaps
Keep the upper median at the root of a min PriorityQueue and the lower half in a negated min PriorityQueue.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(log n)
AverageO(log n)
WorstO(log n)
SpaceO(n)
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Trace source-faithful insertions, median reads, deletions, balancing transfers, and Java integer negation across two binary heaps.
- For even sizes the source selects the upper median, which is rHeap.peek().
- lHeap stores negated int values so its min root represents the largest lower-half value.
- The balance method uses two sequential if statements, and its second check observes any first transfer.
- PriorityQueue breaks equal-value heap ties by leaving a new item in place and preferring the left child on poll.
- Java int negation wraps for Integer.MIN_VALUE; an empty peek or poll throws while unboxing null.
Algorithm code
Javasorting/MedianHeap.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1