Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Heaps & Priority Queues

Two Heaps

O(log n) per op

A max-heap holds the lower half, a min-heap the upper half; keep their sizes balanced and the median sits on top.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn firstTop-K Elements
0%
mastery
0/5 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Running median, sliding-window median, or two pools picked by different keys (IPO: affordable vs most profitable).

  1. 1Brute force

    Sort after each insertion.

  2. 2The observation

    Re-sorting: only the boundary between the halves matters.

  3. 3Why it works

    Every element in the low max-heap <= every element in the high min-heap, and their sizes differ by at most one.

Reach for it when

  • +sliding window median
  • +two pools selected by different keys (IPO: affordable vs profitable)

Not when

  • ×Arbitrary deletions without lazy-delete bookkeepinguse Ordered multiset
  • ×You need the k-th element for arbitrary k, not just the middleuse Order-statistic tree or BIT

Practice

Next · Foundation

Find Median from Data Stream

Max-heap low, min-heap high, sizes differ by <= 1.

0/5 solved
  • Find Median from Data StreamFoundationFoundationAmazon, GoogleHard
  • Sliding Window MedianTwists · Elements also leave.TwistsHard
  • IPOBranches · Two heaps keyed differently (capital vs profit).BranchesCitadel, Goldman SachsHard
  • Sliding Window MedianMastery checkMastery checkCSESMedium
  • Sliding Window CostCSESMedium

Pitfalls

Classic bugs

  • !Forgetting to rebalance after every insert: push to one side, move its top across, then fix sizes so they differ by <= 1.
  • !Sliding-window median: heaps can't delete by value; keep lazy-delete counts and purge tops when they're stale.
Go deeperresources

Resources

  • Heap visualizerVisuAlgo · tool
  • Heap cheatsheetTech Interview Handbook · article
  • std::priority_queuecppreference · docs
  • Find Median from Data Stream editorialLeetCode · editorial
  • Heaps and Heap SortAbdul Bari · video
Top-K ElementsK-way Merge
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial