Loading
Loading
Constant-time access to the extreme, logarithmic to change it.
A binary heap keeps the smallest (or largest) element at the root while only partially ordering everything else. That weaker guarantee is exactly why insertion and removal cost O(log n) rather than O(n), and it is all you need when the question only ever asks for the current extreme.
A heap is a partially ordered tree, not a sorted list. Only the root is guaranteed. Iterating the backing array will not give you sorted output, and that surprises people.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
import heapq def merge_sorted_lists(lists): """A heap of one candidate per list: always pop the global smallest.""" heap = [] for list_index, values in enumerate(lists): if values: # Carrying the indices lets us refill from the list we drained. heapq.heappush(heap, (values[0], list_index, 0)) result = [] while heap: value, list_index, value_index = heapq.heappop(heap) result.append(value) nxt = value_index + 1 if nxt < len(lists[list_index]): heapq.heappush(heap, (lists[list_index][nxt], list_index, nxt)) return result class RunningMedian: """Two heaps facing each other: a max-heap below, a min-heap above.""" def __init__(self): self.low = [] # max-heap, stored negated self.high = [] # min-heap def add(self, value): heapq.heappush(self.low, -value) # Keep every element in 'low' no greater than every element in 'high'. heapq.heappush(self.high, -heapq.heappop(self.low)) if len(self.high) > len(self.low): heapq.heappush(self.low, -heapq.heappop(self.high)) def median(self): if len(self.low) > len(self.high): return -self.low[0] return (-self.low[0] + self.high[0]) / 2| Status | Problem | Difficulty | Role |
|---|---|---|---|
| How Many Studios?#83 | Medium | Related | |
| Fewest Depot Stops#90 | Hard | Primary | |
| Curriculum Order#103 | Medium | Related | |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in| Medium |
| Primary |
| K-th Loudest Reading#111 | Easy | Related |
| Crush the Heaviest Pair#112 | Easy | Primary |
| Nearest Charging Stations#113 | Medium | Related |
| Merge Sorted Feeds#114 | Medium | Primary |
| Top Search Terms#115 | Medium | Related |
| Running Median of a Stream#116 | Hard | Primary |
| Cable Splicing Cost#117 | Medium | Primary |
| Oven Cooldown Schedule#118 | Medium | Primary |
| Tightest Sensor Window#119 | Hard | Primary |
| K-th Smallest in a Sorted Grid#128 | Medium | Primary |