Two Heaps
Keep a max-heap of the smaller half and a min-heap of the larger half to get running medians and balance two choices.
Split the data into two halves: a max-heap holding the smaller half and a min-heap holding the larger half. The two heap tops sit right at the middle, so the median is always available in O(1), and each insert costs O(log n).
- Median of a stream, or of a sliding window.
- Problems that need the "largest of the small ones" and the "smallest of the large ones" at the same time.
- Scheduling with two competing orders: e.g. IPO — projects you can afford (sorted by capital) vs. the most profitable one among them.
Find median from a data stream
Invariants: every element of lo is ≤ every element of hi, and lo has the same size as hi or one more.
class MedianFinder {
PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder()); // max-heap
PriorityQueue<Integer> hi = new PriorityQueue<>(); // min-heap
void addNum(int x) {
lo.offer(x);
hi.offer(lo.poll()); // move lo's largest to hi (keeps order)
if (hi.size() > lo.size()) lo.offer(hi.poll()); // rebalance sizes
}
double findMedian() {
return lo.size() > hi.size() ? lo.peek() : (lo.peek() + hi.peek()) / 2.0;
}
}import heapq
class MedianFinder:
def __init__(self):
self.lo = [] # max-heap via negated values
self.hi = [] # min-heap
def add_num(self, x):
heapq.heappush(self.lo, -x)
heapq.heappush(self.hi, -heapq.heappop(self.lo))
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
def find_median(self):
if len(self.lo) > len(self.hi):
return -self.lo[0]
return (-self.lo[0] + self.hi[0]) / 2// Assumes a small Heap<T> class with push/pop/peek/size and a comparator.
class MedianFinder {
lo = new Heap<number>((a, b) => b - a); // max-heap
hi = new Heap<number>((a, b) => a - b); // min-heap
addNum(x: number) {
this.lo.push(x);
this.hi.push(this.lo.pop()!);
if (this.hi.size > this.lo.size) this.lo.push(this.hi.pop()!);
}
findMedian(): number {
return this.lo.size > this.hi.size ? this.lo.peek()! : (this.lo.peek()! + this.hi.peek()!) / 2;
}
}Sliding window median
You also need to remove the element leaving the window. Heaps can't delete arbitrary items cheaply, so use lazy deletion: record the outgoing value in a "to delete" map and discard it when it surfaces at a heap top. Keep sizes balanced by counting only valid elements. Alternatives: two TreeMap/multisets (Java, C++), or SortedList in Python. Time O(n log k).
IPO (maximise capital)
Sort projects by required capital. Repeat k times: push every newly affordable project's profit onto a max-heap, then take the most profitable one. One "heap" here is the sorted array with a pointer, the other is the max-heap.
int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
int n = profits.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> capital[a] - capital[b]);
PriorityQueue<Integer> best = new PriorityQueue<>(Collections.reverseOrder());
int i = 0;
while (k-- > 0) {
while (i < n && capital[idx[i]] <= w) best.offer(profits[idx[i++]]);
if (best.isEmpty()) break;
w += best.poll();
}
return w;
}def find_maximized_capital(k, w, profits, capital):
projects = sorted(zip(capital, profits))
best, i = [], 0
for _ in range(k):
while i < len(projects) and projects[i][0] <= w:
heapq.heappush(best, -projects[i][1])
i += 1
if not best:
break
w -= heapq.heappop(best)
return wfunction findMaximizedCapital(k: number, w: number, profits: number[], capital: number[]): number {
const projects = capital.map((c, i) => [c, profits[i]]).sort((a, b) => a[0] - b[0]);
const best = new Heap<number>((a, b) => b - a);
let i = 0;
while (k-- > 0) {
while (i < projects.length && projects[i][0] <= w) best.push(projects[i++][1]);
if (!best.size) break;
w += best.pop()!;
}
return w;
}- Find Median from Data Streamhard
- Sliding Window Medianlazy deletionhard
- IPOsorted capital + max-heap of profithard
- Find Right Intervaltwo heaps or sort + binary searchmedium
- Kth Largest Element in a Streamone heap of size keasy
- Max-heap for the lower half, min-heap for the upper half; the tops are the median.
- Keep sizes equal or
loone larger; push throughlotohito keep order. - Sliding windows need lazy deletion or an ordered multiset.
- The same "two priority orders" idea solves scheduling problems like IPO.
QWhy not just keep a sorted list and insert into it?medium
Insertion into a sorted array is O(n) because elements shift. Two heaps make each insert O(log n) and still give the median in O(1). A balanced BST or skip list also works and supports deletions, at a higher constant cost.
QHow would you handle the median when 99% of numbers fall in 0–100?hard
Keep a count array for 0–100 and find the median by walking cumulative counts (O(100)). Put rare outliers into small separate lists or heaps and adjust the median rank by their counts.