DSAVisualiseData Structures & Algorithms Studio
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 JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

Source scenarios

Complexity

BestO(log n)
AverageO(log n)
WorstO(log n)
SpaceO(n)

Array state

Follow the active comparisons and writes.

Live snapshot

Current operation

Trace state
Ready 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

Java
sorting/MedianHeap.javaStep linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1