Home
Log in
DescriptionSubmissionsSolution
DescriptionSubmissionsSolution
Loading...

Log in to run or submit

operations =
arguments =

Codey

Practise coding problems, test your solutions and track your progress.

Explore

  • Problems
  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

© 2026 Codey. Personal learning project.

Solution
Updated: 2026-02-23

Idea

Maintain two heaps: lower half (max-heap) and upper half (min-heap).

Approach

  • Push into max-heap, then move its top into min-heap.
  • Rebalance so max-heap has equal or one more element than min-heap.
  • Median is either top of max-heap (odd count) or average of both tops.

Why it works

Heaps keep halves ordered: all small <= large, and sizes differ by at most 1.

Code
Loading...
Complexity
Time: O(log n) per add, O(1) median
Space: O(n)
Solution
Updated: 2026-02-23

Idea

Maintain two heaps: lower half (max-heap) and upper half (min-heap).

Approach

  • Push into max-heap, then move its top into min-heap.
  • Rebalance so max-heap has equal or one more element than min-heap.
  • Median is either top of max-heap (odd count) or average of both tops.

Why it works

Heaps keep halves ordered: all small <= large, and sizes differ by at most 1.

Code
Loading...
Complexity
Time: O(log n) per add, O(1) median
Space: O(n)