Python 3D Academyবাংলা

Merging k sorted lists; the running median with two heaps

🌍 In real life. Three class teachers each hand the office a list of marks, already sorted from lowest to highest. To make one sorted list for the whole year, the office never needs to sort again. It looks only at the front of each list, takes the smallest of those three, and moves that list on by one.

And a property website shows the median house price, the middle one, after every new sale. Re-sorting all the prices after each sale would be slow. Keeping the cheaper half and the dearer half in two heaps puts the middle right at their two tops.

Both jobs use a heap to watch only a few candidates at a time.

The idea in one sentence: to merge k sorted lists, keep one item per list (its current front) in a min-heap and repeatedly pop the smallest and push the next item from the same list; for the running median, keep the smaller half in a max-heap and the bigger half in a min-heap, balanced in size, so the median is at the tops.

Its words:

  • k-way merge: merging k sorted lists at once
  • front: the next unused value of a list
  • median: the middle value of the numbers sorted; with an even count, the average of the two middle ones
  • running median: the median after each new number of a stream
  • two heaps: a max-heap for the smaller half (in Python, push -x) and a min-heap for the bigger half

How the running median works, step by step, for each new number x:

  1. if x is no bigger than the top of the smaller half (or that half is empty), push it there; otherwise push it into the bigger half
  2. if the smaller half has two more than the bigger half, move its top across; if the bigger half has more, move its top back
  3. the median is the smaller half's top when the count is odd, and the average of the two tops when it is even

Watch 5, 15, 1, 3, 8 arrive:

Why it is correct. Merging: every list is sorted, so the smallest value not yet taken is always at the front of some list. The heap holds exactly those fronts, so popping it gives the right next value. Pushing that list's next value keeps the heap holding all the fronts. The median: the two heaps always split the numbers so that everything in the smaller half is ≤ everything in the bigger half. A new number goes to the side its value belongs on, and moving a top across never breaks the split, because the top is the boundary value. The sizes stay equal or one more on the smaller side, so the middle of the sorted numbers is at the top of the smaller half (odd count) or between the two tops (even count).

What it costs, by counting. Merging N values from k lists: each value is pushed and popped once, on a heap of at most k items, so O(N log k). Putting everything in one list and sorting is O(N log N), and Python's heapq.merge does the heap merge for you. The median: each new number costs a few pushes and pops, O(log n), and reading the median is O(1). The simple alternative keeps one sorted list and puts each number in its place with bisect.insort: finding the place takes about 13 comparisons among 10,000 numbers, but making room shifts up to 10,000 items, so it is O(n) per number. The two heaps do a few pushes and pops of about 13 levels each: O(log n).

import heapq

def merge_sorted(lists):
    heap = []
    for i, lst in enumerate(lists):
        if lst:
            heapq.heappush(heap, (lst[0], i, 0))          # the front of each list
    out = []
    while heap:
        value, i, j = heapq.heappop(heap)                 # the smallest front of all
        out.append(value)
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))   # that list's next value
    return out

print(merge_sorted([[1, 4, 9], [2, 3, 10], [5]]))
print(merge_sorted([[], [3], []]))
print(list(heapq.merge([1, 4, 9], [2, 3, 10], [5])))   # the ready-made version

import heapq

def running_medians(stream):
    low, high, out = [], [], []          # low: the smaller half, negated (a max-heap)
    for x in stream:
        if not low or x <= -low[0]:
            heapq.heappush(low, -x)
        else:
            heapq.heappush(high, x)
        if len(low) > len(high) + 1:     # keep the sizes equal, or one more in low
            heapq.heappush(high, -heapq.heappop(low))
        elif len(high) > len(low):
            heapq.heappush(low, -heapq.heappop(high))
        out.append(-low[0] if len(low) > len(high) else (-low[0] + high[0]) / 2)
    return out

print(running_medians([5, 15, 1, 3, 8]))

Mistakes and edge cases.

  • pushing only values when merging: the heap must also remember which list a value came from and where, or you can't fetch that list's next value; push (value, list_index, position)
  • equal values when merging: the list index in the tuple breaks ties, so Python never has to compare anything else
  • empty lists: skip them when filling the heap, or lst[0] raises IndexError
  • forgetting the minus signs: heapq only makes min-heaps; the smaller half stores -x, so its biggest is -low[0]
  • letting the halves drift: without the rebalancing step one heap grows much bigger and the tops are no longer the middle
  • the median of an even count: it is the average of two values, a float in Python ((3 + 5) / 2 is 4.0)

Quiz

  1. What does this print?

    import heapq
    
    def merge_sorted(lists):
        heap = []
        for i, lst in enumerate(lists):
            if lst:
                heapq.heappush(heap, (lst[0], i, 0))          # the front of each list
        out = []
        while heap:
            value, i, j = heapq.heappop(heap)                 # the smallest front of all
            out.append(value)
            if j + 1 < len(lists[i]):
                heapq.heappush(heap, (lists[i][j + 1], i, j + 1))   # that list's next value
        return out
    
    print(merge_sorted([[1, 4, 9], [2, 3], [5]]))
  2. When merging, why push (value, list index, position) instead of just the value?

    • After popping a value you need to know which list to take the next value from, and from where
    • heapq can't store plain numbers
    • It makes the heap smaller
  3. What does this print?

    import heapq
    
    def running_medians(stream):
        low, high, out = [], [], []          # low: the smaller half, negated (a max-heap)
        for x in stream:
            if not low or x <= -low[0]:
                heapq.heappush(low, -x)
            else:
                heapq.heappush(high, x)
            if len(low) > len(high) + 1:     # keep the sizes equal, or one more in low
                heapq.heappush(high, -heapq.heappop(low))
            elif len(high) > len(low):
                heapq.heappush(low, -heapq.heappop(high))
            out.append(-low[0] if len(low) > len(high) else (-low[0] + high[0]) / 2)
        return out
    
    print(running_medians([2, 1, 5]))
  4. In the running median, why is the smaller half kept in a max-heap?

    • The median needs the biggest of the smaller half, and a max-heap keeps that on top
    • Max-heaps are faster than min-heaps
    • So that the two heaps hold different types
  5. Merging k sorted lists holding N values in all, with a heap: what is the running time?

    • O(N log k)
    • O(N log N)
    • O(N k)
  6. merge_sorted([[1, 4, 9], [2, 3, 10], [5]]) should give [1, 2, 3, 4, 5, 9, 10], but gives [1, 1, 2, 2, 3, 4, 5]. Which line is wrong?

    import heapq
    
    def merge_sorted(lists):
        heap = []
        for i, lst in enumerate(lists):
            if lst:
                heapq.heappush(heap, (lst[0], i, 0))
        out = []
        while heap:
            value, i, j = heapq.heappop(heap)
            out.append(value)
            if j + 1 < len(lists[i]):
                heapq.heappush(heap, (lists[i][j], i, j + 1))
        return out

Coding tasks

  1. Write merge_sorted(lists): lists is a list of sorted lists (some may be empty); return one sorted list of all their values. Use a heap of each list's front; don't call sorted() or .sort().

  2. Write running_medians(stream): a list with the median after each number of stream. With an odd count it is the middle number; with an even count, the average of the two middle numbers (a float, as / gives). Use two heaps.