Heaps and Priority Queues Questions
Binary heaps and priority queues as data structures: min-heap and max-heap, array layout, sift-up and sift-down, push/pop/peek costs, build-heap (heapify) in O(n), and indexed heaps with decrease-key versus lazy deletion of stale entries. Covers the problems where a heap is the intended tool: top-K and kth largest or smallest selection (including over a one-pass stream and under inserts and deletes), sorting an array whose elements are at most k places out of order with a window heap, the two-heap pattern for running and sliding-window medians (invariants, rebalancing, lazy deletion, testing, and extensions to percentiles, weighted medians, custom orderings and merging structures), k-way merge of sorted lists, arrays, files or streams with bounded memory, scheduling by priority with cancellation and reprioritisation, stable priority queues with tie-breaking, and implementing a heap or priority queue with a language library such as heapq or PriorityQueue (including max-heap behaviour from a min-heap). Boundary: graph shortest-path algorithms, approximate quantile sketches, production streaming-system design, and heapsort and quickselect as sorting and selection algorithms are covered elsewhere.
Implement a RunningMedian class in Python with add(num) and get_median(). Each add should be O(log n) and get_median O(1). Handle even and odd counts, duplicates, and a call to get_median on an empty stream, and state the complexity of your solution.
Sample Answer
The idea
The median is the middle of the sorted values, so you never need the full order, only the middle. Keep two heaps (a heap is a tree stored in an array that always gives you its smallest or largest item in O(1) and updates in O(log n)): a max-heap low holding the smaller half and a min-heap high holding the larger half. The largest of low and the smallest of high are the two values next to the middle, so the median is one of them or their average.
The rules that must hold after every add (an invariant is a rule that is true before and after each operation):
- every value in
lowis less than or equal to every value inhigh; len(low)equalslen(high), or exceeds it by exactly one.
Brute force and why it is not enough
Appending to a list and sorting on every query costs O(n log n) per query. Inserting with bisect.insort keeps the list sorted but shifts elements, so each add is O(n). The two-heap version makes add O(log n) and get_median O(1).
Approach
- Route: if
numis greater than the top oflow, it belongs in the upper half (high); otherwise it goes inlow. Ties go tolow, which keeps the routing deterministic and duplicates harmless. - Rebalance: if
lownow has two more items thanhigh, move its top across; ifhighhas more items thanlow, move its top across. At most one move is needed because a single insert changes one size by one. - Read: if
lowis larger, the count is odd and the median is the top oflow; otherwise average the two tops. An empty stream raisesValueError, because no median exists and returning 0 would hide a bug.
Python's heapq is a min-heap in Python 3.12 and every release before 3.14 (3.14 added _max functions such as heappush_max, but negation works on every version), so low stores negated values: -low[0] is the largest value in the lower half.
The core of the class is the routing and rebalancing inside add plus get_median. Two extras sit around that core. The first lines of add reject input that would corrupt the heaps: bool is excluded because True would silently count as 1, numbers.Real accepts ints, floats and other real-number types such as fractions.Fraction, but not complex numbers or strings, and math.isnan catches NaN (not-a-number, a float that compares false against everything, so it would break the heap ordering). The running_medians generator (a function that uses yield to hand back one result at a time) simply calls add then get_median for each element of a stream and produces the median after every step.
import heapq
import math
from numbers import Real
class RunningMedian:
"""Two heaps: `low` is a max-heap (values negated), `high` is a min-heap.
Invariant: len(low) == len(high) or len(low) == len(high) + 1,
and every value in low <= every value in high."""
def __init__(self):
self.low = []
self.high = []
def add(self, num):
if isinstance(num, bool) or not isinstance(num, Real) or math.isnan(num):
raise TypeError(f"expected a real number, got {num!r}")
if self.low and num > -self.low[0]:
heapq.heappush(self.high, num) # belongs to the upper half
else:
heapq.heappush(self.low, -num) # belongs to the lower half (ties go here)
# rebalance so that len(low) is len(high) or len(high) + 1
if len(self.low) > len(self.high) + 1:
heapq.heappush(self.high, -heapq.heappop(self.low))
elif len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def get_median(self):
if not self.low:
raise ValueError("median of an empty stream is undefined")
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
def running_medians(stream):
rm = RunningMedian()
for x in stream:
rm.add(x)
yield rm.get_median()
if __name__ == "__main__":
rm = RunningMedian()
try:
rm.get_median()
except ValueError as e:
print("empty:", e)
for x in [5, 5, 1, 9, 5, 2]:
rm.add(x)
print(f"add {x}: low={sorted(-v for v in rm.low)} high={sorted(rm.high)} median={rm.get_median()}")
print(list(running_medians([2, 1, 3, 4])))
try:
rm.add("7")
except TypeError as e:
print("bad input:", e)
Output:
empty: median of an empty stream is undefined
add 5: low=[5] high=[] median=5
add 5: low=[5] high=[5] median=5.0
add 1: low=[1, 5] high=[5] median=5
add 9: low=[1, 5] high=[5, 9] median=5.0
add 5: low=[1, 5, 5] high=[5, 9] median=5
add 2: low=[1, 2, 5] high=[5, 5, 9] median=5.0
[2, 1.5, 2, 2.5]
bad input: expected a real number, got '7'
Worked trace (from the output above)
add 5: stream 5.low= {5},high= {}. One value, median is the top oflow: 5.add 5(a duplicate): 5 is not greater than the top oflow(5), so it goes tolow, making sizes 2 and 0. Rebalancing moves one 5 tohigh:low= {5},high= {5}, median (5 + 5) / 2 = 5.0.add 1: 1 goes tolow, givinglow= {1, 5},high= {5}. Sizes 2 and 1 are allowed. Median is the top oflow, 5.add 9: 9 is greater than 5, so it goes tohigh:low= {1, 5},high= {5, 9}. Median (5 + 5) / 2 = 5.0.add 5: 5 is not greater than the top oflow(5), so it goes tolow:low= {1, 5, 5},high= {5, 9}. Sizes 3 and 2 are allowed. Median is the top oflow, 5.add 2: 2 is not greater than 5, so it goes tolow, givinglow= {1, 2, 5, 5} (size 4) andhigh= {5, 9} (size 2).lowhas two more items thanhigh, so its top (5) moves across:low= {1, 2, 5},high= {5, 5, 9}. Sizes 3 and 3, median (5 + 5) / 2 = 5.0.
Complexity
add: a constant number ofheappush/heappopcalls on heaps of at most n items, each O(log n), so O(log n).get_median: reads at most two array positions, O(1).- Space: O(n), since every value is stored once.
- The generator
running_mediansyields after each element, so processing a whole stream costs O(n log n) total, against O(n^2) or O(n^2 log n) for re-sorting.
Edge cases handled
- Empty stream:
ValueErrorfromget_median. - One element: the median is that element.
- Duplicates: ties route to
lowand the size rule is about counts, so repeated values never break anything. - Even versus odd counts: the even case returns a float (
/ 2), the odd case returns the stored value. - Non-numeric input (strings,
bool, NaN):TypeErroratadd. A NaN would be stored without error but compares false against everything, which silently breaks the heap ordering, so it is rejected up front.
Common mistakes
- Comparing against the wrong heap's top, or forgetting the negation when comparing with
-low[0]. - Rebalancing by size before routing by value, which can leave a large number in the lower half.
- Using
//for the average and truncating 2.5 to 2.
Running the code
python3 running_median.py
Python 3.12, standard library only.
You have two heaps: lowers (max-heap) contains [5, 3, 2], highers (min-heap) contains [6, 8, 9]. Show the steps and resulting heaps after inserting value 7, including any rebalancing required. Explain your decision at each step.
Sample Answer
The idea
Two heaps split the numbers into a lower half and an upper half. lowers is a max-heap (a heap whose top is its largest item) and highers is a min-heap (top is its smallest item). Two rules must hold after each insertion:
- Ordering: every number in
lowersis less than or equal to every number inhighers, i.e. the top oflowers<= the top ofhighers. - Size: the halves are equal in size, or
lowershas exactly one more. (This convention makes the median the top oflowerswhen the count is odd.)
Start: lowers = [5, 3, 2] (top 5), highers = [6, 8, 9] (top 6). Both rules hold: 5 <= 6, and the sizes are 3 and 3. The median of 2, 3, 5, 6, 8, 9 is (5 + 6) / 2 = 5.5.
Steps for inserting 7
Step 1: decide which half 7 belongs to. Compare with the top of lowers. If 7 were less than or equal to 5 it would go in lowers; it is larger, so it goes in highers. Putting it there cannot break the ordering rule, because 7 is at least as big as everything in lowers. highers becomes {6, 7, 8, 9} with top 6.
Step 2: check the sizes. lowers has 3 items and highers has 4. The size rule says highers may never have more items than lowers, so this breaks it.
Step 3: rebalance by moving one item. Pop the top of highers (6, the smallest of the upper half) and push it into lowers. Moving the smallest of the upper half is the only safe choice: it is at least as big as everything in lowers and no bigger than anything left in highers, so ordering still holds. The tops become 6 and 7, and 6 <= 7.
Step 4: read the result. Sizes are now 4 and 3, which is allowed. With 7 numbers (2, 3, 5, 6, 7, 8, 9) the median is the top of lowers, 6.
The script below runs these four steps, numbered the same way, on real heapq heaps (the max-heap is stored negated because heapq is a min-heap) and prints the state after each one:
import heapq
lowers = [-v for v in (5, 3, 2)] # max-heap, stored negated
highers = [6, 8, 9] # min-heap
heapq.heapify(lowers)
heapq.heapify(highers)
def show(label):
print(f"{label:<34} lowers(max-heap)={sorted((-v for v in lowers), reverse=True)} "
f"top={-lowers[0]} highers(min-heap)={sorted(highers)} top={highers[0]}")
def median():
return -lowers[0] if len(lowers) > len(highers) else (-lowers[0] + highers[0]) / 2
show("start")
x = 7
if x <= -lowers[0]:
heapq.heappush(lowers, -x)
print("step 1: 7 <= 5? yes, goes to lowers")
else:
heapq.heappush(highers, x)
print("step 1: 7 <= 5? no, goes to highers")
show("after step 1")
print(f"step 2: sizes are lowers={len(lowers)} highers={len(highers)}")
if len(highers) > len(lowers):
moved = heapq.heappop(highers)
heapq.heappush(lowers, -moved)
print(f"step 3: highers is larger, move its top {moved} to lowers")
show("after step 3")
print(f"step 4: sizes are lowers={len(lowers)} highers={len(highers)}, median={median()}")
start lowers(max-heap)=[5, 3, 2] top=5 highers(min-heap)=[6, 8, 9] top=6
step 1: 7 <= 5? no, goes to highers
after step 1 lowers(max-heap)=[5, 3, 2] top=5 highers(min-heap)=[6, 7, 8, 9] top=6
step 2: sizes are lowers=3 highers=4
step 3: highers is larger, move its top 6 to lowers
after step 3 lowers(max-heap)=[6, 5, 3, 2] top=6 highers(min-heap)=[7, 8, 9] top=7
step 4: sizes are lowers=4 highers=3, median=6
Final heaps: lowers = {6, 5, 3, 2} (top 6), highers = {7, 8, 9} (top 7).
Why not other moves
- Pushing 7 straight into
lowerswould put 7 above 6, the smallest ofhighers, and break the ordering rule. - Rebalancing by moving the top of
lowers(5) intohighersis the move for the opposite imbalance, and here it would make the size gap worse. - Under a looser rule (sizes may differ by one in either direction) the 3 versus 4 split is already legal and step 3 is skipped; the median is then the top of
highers, which is also 6. Pick one convention and keep it, becausemedian()depends on it.
Complexity and mistakes
Insertion and rebalancing are a constant number of heap operations, so O(log n) per insert, with O(1) to read the median. Common mistakes: forgetting that a move changes both heaps (pop from one and push to the other), and rebalancing before routing by value.
Running the code
python3 insert_trace.py
Python 3.12, standard library only.
An array of n integers has the property that every element is at most k positions away from where it would be in sorted order. Sort it efficiently. Which approach do you choose, how does a heap of size k+1 make it work, and what are the time and space complexities compared with a general sort when k is small?
Sample Answer
The idea in plain words
A list is "k-sorted" when every value sits at most k positions away from the spot it would occupy in the fully sorted list. Because values cannot wander far, you never need to look at the whole input to decide the next output value. Keep a min-heap (a tree stored in an array where the smallest value is always readable at the top in O(1), and inserting or removing costs O(log size)) holding a sliding window of k+1 values. The smallest value in the window is the next value of the sorted output.
Why a window of k+1 is enough
Count output positions from 0 and take position i. The value that belongs there started at an index of at most i+k, so once indexes 0 through i+k have been read it is either already written out or still in the heap. It cannot be written out already, because every written value belongs to an earlier position. So it is in the heap. It is also the smallest value in the heap, because every value still in the heap belongs at position i or later. Hence the heap minimum is final at that moment. Reading indexes 0 through i+k is i+k+1 values, and i of them have already been written, so the heap holds exactly k+1 values when position i is chosen.
A concrete instance with k = 2 on [3, 1, 2, 6, 4, 5]. Position 0 must receive 1, which started at index 1, within 0 + 2. After reading indexes 0 to 2 the heap holds {3, 1, 2}, which is k+1 = 3 values, and its minimum 1 is final: the 3 and the 2 belong at positions 2 and 1, so neither can undercut it, and every unread value (indexes 3 and up) belongs at position 1 or later. After 1 is written, reading index 3 (the value 6) gives the heap {3, 2, 6}, whose minimum 2 is the value for position 1, and so on.
The code goes one value further: heappushpop lets the next unread value compete with the heap top before the pop. That value sits at index i+k+1, so it belongs at position i+1 or later and never beats the true minimum; the heap itself never stores more than k+1 values.
Choice and brute force
- Sorting everything:
sorted(nums)is O(n log n) time and ignores the structure in the input. - Insertion sort (slide each element left into place among the elements before it): moves each element at most k places, so O(n k) time and O(1) extra space. It beats the heap only for a tiny constant k.
- Heap of size k+1: each of the n elements is pushed and popped once on a heap of at most k+1 entries, so O(n log k) time. That is the choice when k is small relative to n, and it also works when the input arrives as a stream (values come one at a time and the rest cannot be seen yet).
Approach
- Copy the first k+1 elements into a list and turn it into a heap with
heapify(a bottom-up build in one pass, O(k): most nodes sit near the bottom and move only a step or two, whereas k separate pushes would cost O(k log k)). - For every remaining element, call
heappushpop: it pushes the new value and pops the minimum in one step. Append the popped value to the output. - When the input runs out, pop the heap until empty. Each pop yields the next smallest value.
Code
import heapq
import random
def sort_k_sorted(nums, k, trace=False):
"""Sort a list where each element is at most k positions from its sorted place."""
if k < 0:
raise ValueError("k must be >= 0")
heap = nums[: k + 1] # copy of the first k+1 elements: O(k)
heapq.heapify(heap)
if trace:
print(f"seed heap {sorted(heap)}")
result = []
for i in range(k + 1, len(nums)):
incoming = nums[i]
smallest = heapq.heappushpop(heap, incoming) # push incoming, pop minimum
result.append(smallest)
if trace:
print(f"read {incoming:>2} emit {smallest:>2} heap {sorted(heap)}")
while heap:
smallest = heapq.heappop(heap)
result.append(smallest)
if trace:
print(f"drain emit {smallest:>2} heap {sorted(heap)}")
return result
nums = [2, 1, 4, 3, 6, 5, 8, 7]
print(sort_k_sorted(nums, 1, trace=True))
print(sort_k_sorted([3, 1, 2, 6, 4, 5], 2, trace=True)) # k = 2: window of 3
print(sort_k_sorted([1, 2, 3, 4], 0)) # k = 0: already sorted
print(sort_k_sorted([3, 1, 2], 10)) # k >= n: behaves like heap sort
print(sort_k_sorted([], 2)) # empty input
print(sort_k_sorted([5, 5, 4, 4, 6], 2)) # duplicates
# Check against sorted() on random inputs: shuffle each block of k+1 values of a sorted list,
# so every element ends up at most k places from its sorted position.
random.seed(7)
for _ in range(500):
n = random.randint(0, 30)
k = random.randint(0, 6)
data = sorted(random.randint(-9, 9) for _ in range(n))
expected = list(data)
for start in range(0, n, k + 1):
block = data[start : start + k + 1]
random.shuffle(block)
data[start : start + k + 1] = block
assert sort_k_sorted(data, k) == expected
print("500 random checks passed")
Output:
seed heap [1, 2]
read 4 emit 1 heap [2, 4]
read 3 emit 2 heap [3, 4]
read 6 emit 3 heap [4, 6]
read 5 emit 4 heap [5, 6]
read 8 emit 5 heap [6, 8]
read 7 emit 6 heap [7, 8]
drain emit 7 heap [8]
drain emit 8 heap []
[1, 2, 3, 4, 5, 6, 7, 8]
seed heap [1, 2, 3]
read 6 emit 1 heap [2, 3, 6]
read 4 emit 2 heap [3, 4, 6]
read 5 emit 3 heap [4, 5, 6]
drain emit 4 heap [5, 6]
drain emit 5 heap [6]
drain emit 6 heap []
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
[1, 2, 3]
[]
[4, 4, 5, 5, 6]
500 random checks passed
Worked trace
The first run above is the input [2, 1, 4, 3, 6, 5, 8, 7] with k = 1, so the window holds 2 values. The seed heap is [1, 2]. Reading 4 pushes it in and pops 1. Reading 3 pops 2, and so on: each line shows the value read, the value emitted and the heap contents (sorted only for display). The last two lines drain the heap, giving 7 and 8, and the result is [1, 2, 3, 4, 5, 6, 7, 8]. The second run is the k = 2 instance from the proof: the seed heap is [1, 2, 3], reading 6 emits 1, reading 4 emits 2, reading 5 emits 3, and the three drain lines give 4, 5 and 6.
Complexity
- Time: n - k - 1 combined push-pop operations and k + 1 final pops, each O(log(k+1)), plus an O(k) heapify. Total O(n log k) for k >= 1, and O(n) when k = 0. A general sort is O(n log n), so for k much smaller than n the heap saves a factor of about log n / log k.
- Space: the heap holds k+1 values, so O(k) auxiliary space. The output list is O(n), which a general sort also needs unless it sorts in place. If the output may be written to a file or consumed as it is produced, total memory stays O(k).
Edge cases and common mistakes
- k = 0: the window has one element; every push-pop returns the value just pushed, so the input is returned unchanged (the code handles it, shown above).
- k >= n: the window is the whole input and the algorithm becomes heap sort (push everything into a heap, then pop it all in order; O(n log n)).
- Empty input and duplicates give correct output, as the driver shows.
- Choosing each output from fewer than k+1 candidates is the usual off-by-one. With k = 1 on [2, 1], a version that emits the minimum of a one-value heap before reading the next value outputs 2 then 1, which is wrong. The shipped loop avoids this because
heappushpoplets the incoming value compete before anything is emitted; the proof's window is k+1 values, and seeding with k+1 matches it. - Using
heappushfollowed byheappopis correct, butheappushpopdoes it in one pass and avoids growing the heap to k+2. - Slicing
nums[k+1:]in the loop would copy O(n) values, which is why the code indexes instead.
Running the code
python3 k_sorted.py
Standard library only (Python 3.12). Save the listing as k_sorted.py.
A binary heap supports efficient removal of only its top element. How would you support deleting an arbitrary value from a structure built on heaps, such as a two-heap median? Compare lazy deletion with true removal from the array and with an indexed heap, including the complexity and memory trade-offs.
Sample Answer
The core difficulty
A binary heap is an array arranged so that each parent is smaller (min-heap) or larger (max-heap) than its two children. That layout makes the top easy to reach and to remove: swap the last entry into the root and sift it down, O(log n). It gives no way to find an arbitrary value: the array is only partly ordered, so a value can be anywhere. In a two-heap median (a max-heap for the lower half, a min-heap for the upper half), deleting an arbitrary value, for example to retract a user action or expire a window entry, therefore needs one of three designs.
Two repair moves recur below. Sift up: while an entry is smaller than its parent (in a min-heap), swap it with the parent. Sift down: while an entry is larger than its smaller child, swap it with that child. With the array indexed from 0, the parent of index i is at (i - 1) // 2 and its children are at 2 * i + 1 and 2 * i + 2. Amortized O(log n) means O(log n) per operation when the cost is averaged over a whole sequence, even if a single operation occasionally costs more.
Option 1: true removal from the array
Find the entry, then repair the heap. Finding it is a linear scan (list.index), O(n). The repair is cheap: overwrite its slot with the last array entry, shrink the array, and sift that entry up or down, O(log n). The total is O(n) per delete and no extra memory.
Why up or down: the last entry comes from a different branch of the tree, so it can be smaller than its new parent (then it must go up) or larger than its new children (then it must go down). It can never need both, so running both is safe: one of them does nothing. Take the 7-entry min-heap [1, 5, 2, 6, 7, 3, 4] (a parent sits at index (i - 1) // 2, so 5 and 2 are the children of 1, 6 and 7 the children of 5, and 3 and 4 the children of 2). Delete 6, at index 3. The last entry, 4, takes its slot; its new parent is 5, and 4 is smaller, so it swaps up: [1, 4, 2, 5, 7, 3]. Now delete the root, 1. The last entry, 3, takes the root slot; its children are 4 and 2, and 3 is larger than the smaller one, 2, so it swaps down: [2, 4, 3, 5, 7]. The program below prints exactly these two steps. The scan dominates, as the measurement below shows.
Option 2: lazy deletion
Do not look for the entry. Mark its id (or its value, with a counter) as dead and leave it in place. Dead entries are discarded when they reach the top of a heap, where heappop removes them in O(log n). Two bookkeeping rules make this correct for a median: balance with the logical (live) sizes and not the array lengths, and always clear dead entries off the tops before reading the median.
- Time: the delete itself is a set insert plus at most one O(log n) rebalance move. Each entry is popped at most once, and that pop is charged to its own insertion (the O(log n) cost of discarding a dead entry is attributed to the push that created it), so deletes are O(log n) amortized.
- Memory: a dead entry is freed only when it surfaces. Entries at the bottom of a heap may never surface, so physical size is O(total inserted) in the worst case, plus the set of dead ids.
Option 3: an indexed heap
Keep a dictionary pos from item id to its current array index, updated on every swap. Then deleting any item is: look up its index in O(1), overwrite with the last entry, sift up or down, O(log n) worst case, and no dead entries ever exist, so the heap size is exact and the median needs no live counters.
- Time: O(log n) worst case per delete, but every push, pop and swap also writes the dictionary.
- Memory: one extra dictionary entry per live item (plus a side map in the median to know which half holds an id), and the arrays stay at the live size.
The code
IndexedHeap keeps the array a of (key, item_id) pairs and the dictionary pos. _swap is the only place two entries trade places, and it rewrites both pos entries, so pos is always correct. remove pops the item's slot out of pos, moves the last array entry into the hole, fixes that entry's pos, and then calls _sift_up and _sift_down as described above; pop is just remove of the top. swaps counts the swaps so the cost table can report them.
The file contains an indexed heap, a two-heap median built on it, a lazy two-heap median with the same interface, a check of both against a brute-force median over random add and remove sequences (removals pick an arbitrary live item, not the oldest), a measurement of the cost of finding an entry versus repairing the heap, a memory comparison, and a printed trace of the 7-entry removal example above.
import heapq
import random
class IndexedHeap:
"""Min-heap of (key, item_id) that also remembers where each item_id sits in the array."""
def __init__(self):
self.a = []
self.pos = {} # item_id -> index in self.a
self.swaps = 0 # counts every swap done while sifting
def __len__(self):
return len(self.a)
def _swap(self, i, j):
a = self.a
a[i], a[j] = a[j], a[i]
self.pos[a[i][1]] = i
self.pos[a[j][1]] = j
self.swaps += 1
def _sift_up(self, i):
while i > 0 and self.a[i] < self.a[(i - 1) // 2]:
self._swap(i, (i - 1) // 2)
i = (i - 1) // 2
def _sift_down(self, i):
n = len(self.a)
while True:
smallest = i
for c in (2 * i + 1, 2 * i + 2):
if c < n and self.a[c] < self.a[smallest]:
smallest = c
if smallest == i:
return
self._swap(i, smallest)
i = smallest
def push(self, key, item_id):
self.a.append((key, item_id))
self.pos[item_id] = len(self.a) - 1
self._sift_up(len(self.a) - 1)
def peek(self):
return self.a[0]
def remove(self, item_id):
"""Remove any item in O(log n): move the last entry into its slot, then sift it up or down."""
i = self.pos.pop(item_id)
last = self.a.pop()
if i < len(self.a):
self.a[i] = last
self.pos[last[1]] = i
self._sift_up(i)
self._sift_down(self.pos[last[1]])
def pop(self):
key, item_id = self.a[0]
self.remove(item_id)
return key, item_id
class MedianWithRemoval:
"""Two indexed heaps: exact sizes, so no live counters and no stale entries."""
def __init__(self):
self.small = IndexedHeap() # stores -value, so its top is the largest of the lower half
self.large = IndexedHeap()
self.side = {} # item_id -> the heap holding it
def add(self, item_id, x):
if len(self.small) == 0 or x <= -self.small.peek()[0]:
self.small.push(-x, item_id); self.side[item_id] = self.small
else:
self.large.push(x, item_id); self.side[item_id] = self.large
self._rebalance()
def remove(self, item_id):
self.side.pop(item_id).remove(item_id)
self._rebalance()
def _rebalance(self):
if len(self.small) > len(self.large) + 1:
key, i = self.small.pop(); self.large.push(-key, i); self.side[i] = self.large
elif len(self.small) < len(self.large):
key, i = self.large.pop(); self.small.push(-key, i); self.side[i] = self.small
def median(self):
if len(self.small) > len(self.large):
return float(-self.small.peek()[0])
return (-self.small.peek()[0] + self.large.peek()[0]) / 2
class LazyMedian:
"""Same interface, but removal only marks the id dead; dead entries leave a heap when they reach its top."""
def __init__(self):
self.small, self.large = [], [] # heapq lists of (key, item_id)
self.dead = set()
self.side = {} # item_id -> "s" or "l"
self.live = {"s": 0, "l": 0}
def _top(self, heap):
while heap and heap[0][1] in self.dead:
self.dead.discard(heapq.heappop(heap)[1])
return heap[0] if heap else None
def _move(self, src, dst, src_tag, dst_tag):
key, i = heapq.heappop(src)
heapq.heappush(dst, (-key, i))
self.side[i] = dst_tag
self.live[src_tag] -= 1
self.live[dst_tag] += 1
def _rebalance(self):
if self.live["s"] > self.live["l"] + 1:
self._top(self.small) # make sure the entry we move is alive
self._move(self.small, self.large, "s", "l")
elif self.live["s"] < self.live["l"]:
self._top(self.large)
self._move(self.large, self.small, "l", "s")
self._top(self.small); self._top(self.large) # keep both tops alive for median()
def add(self, item_id, x):
top = self._top(self.small)
if top is None or x <= -top[0]:
heapq.heappush(self.small, (-x, item_id)); self.side[item_id] = "s"; self.live["s"] += 1
else:
heapq.heappush(self.large, (x, item_id)); self.side[item_id] = "l"; self.live["l"] += 1
self._rebalance()
def remove(self, item_id):
tag = self.side.pop(item_id)
self.live[tag] -= 1
self.dead.add(item_id)
self._rebalance()
def median(self):
if self.live["s"] > self.live["l"]:
return float(-self._top(self.small)[0])
return (-self._top(self.small)[0] + self._top(self.large)[0]) / 2
def physical(self):
return len(self.small) + len(self.large)
def brute(values):
w = sorted(values)
n = len(w)
return float(w[n // 2]) if n % 2 else (w[n // 2 - 1] + w[n // 2]) / 2
def worked_removal_example():
"""Remove two items from a 7-entry heap and show the array after each step. Key and id are the same number."""
h = IndexedHeap()
h.a = [(v, v) for v in [1, 5, 2, 6, 7, 3, 4]]
h.pos = {v: i for i, (v, _) in enumerate(h.a)}
show = lambda: [k for k, _ in h.a]
print("start ", show())
h.remove(6) # slot 3 gets the last entry, 4, which is smaller than its new parent 5: it moves up
print("remove 6 (sift up) ", show())
h.remove(1) # the root gets the last entry, 3, which is larger than its smaller child 2: it moves down
print("remove 1 (sift down)", show())
def check_against_brute_force():
rng = random.Random(3)
for _ in range(3000):
indexed, lazy, live = MedianWithRemoval(), LazyMedian(), {}
for step in range(rng.randint(1, 40)):
if live and rng.random() < 0.4:
victim = rng.choice(sorted(live)) # an arbitrary live item, not the oldest
indexed.remove(victim); lazy.remove(victim); del live[victim]
else:
live[step] = rng.randint(-3, 3)
indexed.add(step, live[step]); lazy.add(step, live[step])
if live:
want = brute(live.values())
assert indexed.median() == want and lazy.median() == want
print("indexed and lazy medians match brute force on 3000 random add/remove sequences")
def removal_cost_table():
print(f"{'n':>7} {'avg scan steps (list.index)':>28} {'avg swaps (indexed remove)':>28}")
for n in (1_000, 10_000, 100_000):
rng = random.Random(n)
h = IndexedHeap()
for i in range(n):
h.push(rng.random(), i)
victims = rng.sample(range(n), 200)
scan = 0
before = h.swaps
for v in victims:
scan += h.pos[v] + 1 # entries a linear search compares before finding it
h.remove(v)
print(f"{n:>7} {scan / 200:>28.1f} {(h.swaps - before) / 200:>28.2f}")
def memory_of_lazy_vs_indexed():
window, n = 11, 20_000
indexed, lazy = MedianWithRemoval(), LazyMedian()
peak_indexed = peak_lazy = 0
for i in range(n):
indexed.add(i, i); lazy.add(i, i)
if i >= window:
indexed.remove(i - window); lazy.remove(i - window)
peak_indexed = max(peak_indexed, len(indexed.small) + len(indexed.large))
peak_lazy = max(peak_lazy, lazy.physical())
print(f"window {window}, {n} ascending values: peak entries indexed={peak_indexed}, lazy={peak_lazy}")
if __name__ == "__main__":
worked_removal_example()
check_against_brute_force()
removal_cost_table()
memory_of_lazy_vs_indexed()
Run, it prints:
start [1, 5, 2, 6, 7, 3, 4]
remove 6 (sift up) [1, 4, 2, 5, 7, 3]
remove 1 (sift down) [2, 4, 3, 5, 7]
indexed and lazy medians match brute force on 3000 random add/remove sequences
n avg scan steps (list.index) avg swaps (indexed remove)
1000 427.6 0.90
10000 5108.1 0.86
100000 51106.0 0.94
window 11, 20000 ascending values: peak entries indexed=11, lazy=20000
What the numbers show
- Both designs return the exact median on 3000 random sequences with arbitrary removals.
- Finding an entry by scan takes about half the array on average, so Option 1 is linear. Each figure is the mean over 200 randomly chosen victims. The heap also shrinks from n to n - 200 entries during the run, so the expected mean is a little under n/2 (about 450 for n = 1000), and a 200-victim mean wanders by roughly 2% of n (n divided by the square root of 12 x 200, about 20 for n = 1000). The printed 427.6 for n = 1000, 5108.1 for 10000 and 51106.0 for 100000 all sit within about one such step of that expectation. The indexed repair after the lookup averaged under one swap on this random data; the worst case is O(log n) swaps, one per level.
- With a window of 11 live values and 20000 ascending inserts, the indexed structure holds exactly 11 entries after every removal (12 for an instant between an insert and the matching removal), while the lazy one reaches 20000 physical entries, because the dead entries are the smallest ones and sit at the bottom of the lower-half heap, which is never popped. Both peaks are measured after the removal step.
Comparison and recommendation
| Delete cost | Extra memory | Heap size | Code complexity | |
|---|---|---|---|---|
| True removal, linear scan | O(n) | none | exact | low |
| Lazy deletion | O(log n) amortized | dead ids, plus stale entries | can reach O(inserts) | low to medium |
| Indexed heap | O(log n) worst case | one position entry per item | exact | medium to high |
Recommendation: use lazy deletion when the structure is short-lived or the stream is bounded (an interview solution, a batch job, a window over a modest stream), because it works with the library heap, needs no bookkeeping on every swap, and is easy to get right. Choose the indexed heap when the structure lives for a long time under heavy churn, when memory must stay proportional to the live count, or when you need other operations that address an item by id (decrease-key, change priority). Choose true removal only when n is tiny or deletes are very rare. In an interview, say lazy first, name its memory cost, and offer the indexed heap as the fix.
Pitfalls
- Balancing a lazy structure with
len(heap): dead entries make the lengths wrong. - Forgetting to clear dead entries from the tops after a transfer: the median reads a value that is no longer present.
- Forgetting to update the position map inside every swap of an indexed heap: the next delete removes the wrong entry.
- Deleting by value when duplicates exist: use unique ids (a counter) as the tie-breaker so that one delete removes exactly one copy.
Running the code
python arbitrary_delete.py
Python 3.12, standard library only (heapq, random). No install or config needed.
Implement a function in JavaScript to find the kth most frequent element in an array of integers. Provide a solution optimized for average-case time complexity better than O(n log n) where n is array length. State assumptions and complexity.
Sample Answer
The idea
"The kth most frequent element" means: count how many times each distinct value appears, rank the distinct values from most to least frequent, and return the value at position k. Counting is a single pass with a hash map. The only real question is how to pick rank k out of the counts without sorting all of them.
Assumptions
- Rank is by count, highest first. Ties are broken by whichever value appeared first in the array, so the answer is deterministic. (If your interviewer wants a different tie rule, only the tie-break comparison changes.)
- k is 1-based and must be a positive integer. If there are fewer than k distinct values, the function returns
undefined. - n is the array length and d is the number of distinct values (d <= n).
Brute force and the options
Sorting the counts costs O(d log d), which is O(n log n) when most values are distinct. That is the baseline to beat. The alternatives:
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Sort the (value, count) pairs | O(n + d log d) | O(d) | Simple; worst case O(n log n). |
| Min-heap of size k over the counts | O(n + d log k) | O(d + k) | Faster when k is small. |
| Bucket by frequency | O(n) | O(n) | A count is at most n, so use counts as array indexes. |
| Quickselect on the counts | O(d) average, O(d^2) worst case | O(d) | Pick a pivot count, partition (split) the entries into those ranking above and below it, and continue only in the part that contains rank k; the worst case needs pivots that keep splitting badly, and tie-breaking adds a compare rule. |
The recommended solution is bucketing: it is O(n) in the worst case and has no heap to write. The heap version is included because it is the answer interviewers expect when the counts are huge and k is tiny, since it never holds more than k entries in the heap.
Approach
Bucket: (1) count with a Map, which iterates in insertion order (the order values first appeared); (2) create an array of n + 1 empty lists where buckets[c] holds the values that occurred exactly c times, filled in that order; (3) walk c from n down to 1, counting values as you go, and return the one at rank k.
Heap: keep a min-heap (a tree stored in an array whose root is the smallest item, here "smallest" means worst-ranked) of the k best-ranked values. In the array, the parent of index i sits at index (i - 1) >> 1 (the right shift by one bit halves the number, rounding down) and its children sit at 2i + 1 and 2i + 2. To sift is to move an entry up (swap with its parent) or down (swap with its smaller child) until the order rule holds again. For each distinct value, if the heap has room, add it; otherwise, if the value outranks the root, replace the root. After all values, the root is the worst of the k best, which is exactly rank k.
// Rank distinct values by count (highest first); ties go to the value that appeared first.
// Returns the value at 1-based rank k, or undefined if there are fewer than k distinct values.
function countFirstSeen(nums) {
const counts = new Map(); // a Map iterates in insertion order = order of first appearance
for (const x of nums) counts.set(x, (counts.get(x) ?? 0) + 1);
return counts;
}
// O(n) time, O(n) space: bucket by frequency, then walk from the highest frequency down.
function kthMostFrequentBucket(nums, k) {
if (!Number.isInteger(k) || k < 1) throw new RangeError("k must be a positive integer");
const counts = countFirstSeen(nums);
const buckets = Array.from({ length: nums.length + 1 }, () => []); // buckets[c] = values seen c times
for (const [value, c] of counts) buckets[c].push(value);
let rank = 0;
for (let c = nums.length; c >= 1; c--) {
for (const value of buckets[c]) {
if (++rank === k) return value;
}
}
return undefined;
}
// O(n + d log k) time, O(d + k) space (d = distinct values): a min-heap of the k best-ranked entries.
// "worse" means lower count, or equal count but first seen later.
function kthMostFrequentHeap(nums, k, log = false) {
if (!Number.isInteger(k) || k < 1) throw new RangeError("k must be a positive integer");
const heap = [];
const worse = (a, b) => a.count < b.count || (a.count === b.count && a.first > b.first);
const swap = (i, j) => ([heap[i], heap[j]] = [heap[j], heap[i]]); // destructuring swap, no temp variable
const siftUp = (i) => {
while (i > 0) {
const p = (i - 1) >> 1; // parent of index i; ">> 1" halves a whole number, rounding down
if (!worse(heap[i], heap[p])) break;
swap(i, p);
i = p;
}
};
const siftDown = (i) => {
for (;;) {
let m = i;
const l = 2 * i + 1, r = l + 1; // children of index i are at 2i + 1 and 2i + 2
if (l < heap.length && worse(heap[l], heap[m])) m = l;
if (r < heap.length && worse(heap[r], heap[m])) m = r;
if (m === i) return;
swap(i, m);
i = m;
}
};
let first = 0;
for (const [value, count] of countFirstSeen(nums)) {
const entry = { value, count, first: first++ };
if (heap.length < k) {
heap.push(entry);
siftUp(heap.length - 1);
} else if (worse(heap[0], entry)) { // entry outranks the current kth: replace the root
heap[0] = entry;
siftDown(0);
}
if (log) console.log(` value ${value} (x${count}) -> heap [${heap.map((e) => `${e.value}x${e.count}`).join(", ")}]`);
}
return heap.length === k ? heap[0].value : undefined;
}
// Reference: O(d log d) sort by (count desc, first appearance asc).
function kthMostFrequentSort(nums, k) {
const ranked = [...countFirstSeen(nums)].sort((a, b) => b[1] - a[1]); // stable sort (Node 22): equal counts keep their first-appearance order
return ranked[k - 1]?.[0];
}
const nums = [4, 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 9];
console.log("counts:", [...countFirstSeen(nums)].map(([v, c]) => `${v}x${c}`).join(" "));
console.log("heap steps for k=3:");
kthMostFrequentHeap(nums, 3, true);
for (const k of [1, 2, 3, 4, 5, 6]) {
console.log(`k=${k}: bucket=${kthMostFrequentBucket(nums, k)} heap=${kthMostFrequentHeap(nums, k)} sort=${kthMostFrequentSort(nums, k)}`);
}
console.log("empty array, k=1:", kthMostFrequentBucket([], 1), kthMostFrequentHeap([], 1));
try { kthMostFrequentBucket(nums, 0); } catch (e) { console.log("k=0:", e.message); }
// Randomised agreement check. The generator below is a linear congruential generator: a tiny
// formula that turns the previous number into the next one, so the same seed gives the same run.
// Math.imul multiplies as exact 32-bit integers and & 0x7fffffff keeps 31 bits, i.e. arithmetic mod 2^31.
let seed = 12345;
const rand = () => (seed = (Math.imul(seed, 1103515245) + 12345) & 0x7fffffff) / 2147483648;
for (let t = 0; t < 2000; t++) {
const arr = Array.from({ length: Math.floor(rand() * 20) }, () => Math.floor(rand() * 8) - 3);
const k = 1 + Math.floor(rand() * 6);
const a = kthMostFrequentBucket(arr, k), b = kthMostFrequentHeap(arr, k), c = kthMostFrequentSort(arr, k);
if (a !== c || b !== c) throw new Error(`mismatch ${JSON.stringify(arr)} k=${k}: ${a} ${b} ${c}`);
}
console.log("2000 random arrays: all three agree");
Output:
counts: 4x4 1x2 2x3 3x2 9x1
heap steps for k=3:
value 4 (x4) -> heap [4x4]
value 1 (x2) -> heap [1x2, 4x4]
value 2 (x3) -> heap [1x2, 4x4, 2x3]
value 3 (x2) -> heap [1x2, 4x4, 2x3]
value 9 (x1) -> heap [1x2, 4x4, 2x3]
k=1: bucket=4 heap=4 sort=4
k=2: bucket=2 heap=2 sort=2
k=3: bucket=1 heap=1 sort=1
k=4: bucket=3 heap=3 sort=3
k=5: bucket=9 heap=9 sort=9
k=6: bucket=undefined heap=undefined sort=undefined
empty array, k=1: undefined undefined
k=0: k must be a positive integer
2000 random arrays: all three agree
Worked trace (from the output)
Counts are 4x4 1x2 2x3 3x2 9x1. The ranking is 4 (count 4), then 2 (count 3), then 1 and 3 (both count 2; 1 appeared first), then 9. That is why k=3 gives 1, k=4 gives 3, k=5 gives 9, and k=6 gives undefined. In the bucket version, buckets[4] = [4], buckets[3] = [2], buckets[2] = [1, 3], buckets[1] = [9]; walking down from the top and counting ranks reaches the same answers.
The heap version on the same data with k = 3 (the heap steps for k=3 lines of the output; each entry is valuexcount, and the root, listed first, is the worst-ranked of the kept three):
- Value 4 (count 4) is added:
[4x4]. - Value 1 (count 2) is added and is worse-ranked than 4, so it sifts up to the root:
[1x2, 4x4]. - Value 2 (count 3) is added at the end; it outranks the root 1x2, so it stays below it:
[1x2, 4x4, 2x3]. The heap now holds k = 3 entries. - Value 3 (count 2) ties the root's count but appeared later than 1, so it ranks below the root and is ignored. The heap does not change.
- Value 9 (count 1) ranks below the root and is ignored.
- The root is
1x2, the worst-ranked of the three best, which is rank 3: the answer is 1, as in thek=3line.
Complexity of the shipped code
- Bucket: counting O(n); building n + 1 buckets O(n); the walk visits at most n + d slots. Time O(n), space O(n).
- Heap: counting O(n), then each of d values costs at most O(log k) for a sift (moving an item up or down the tree to restore order). Time O(n + d log k), space O(d) for the map plus O(k) for the heap.
- Both beat a full sort asymptotically when many values are distinct. When k is close to d, the heap's log k approaches log d and the advantage disappears; bucketing stays O(n).
Edge cases and common mistakes
- Empty array: returns
undefinedrather than throwing.kof 0, negative or fractional throws aRangeError. - All values equal: one distinct value, so only k = 1 returns something.
- Ties: without a stated rule, two correct programs can disagree. Note the tie rule out loud.
- Using a plain object instead of
Mapto count: integer-like keys are reordered ascending by the engine and become strings, which breaks first-appearance order and the tie-break. UseMap. - Confusing "kth most frequent element" with "top k most frequent elements". The same counts answer both; for the top k, return all the values in the first k ranks (the heap's contents) instead of only the last.
- Using
sort()on numbers without a comparator in JavaScript, which sorts them as strings.
Running the code
node kth_frequent.js
Node 22, no packages.
Unlock Full Question Bank
Get access to all 28 Heaps and Priority Queues interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.