nlargest, nsmallest, merge
One-liners on top of the heap. nlargest/nsmallest return the top k items (with key=) in O(n log k); merge lazily merges already-sorted iterables, the built-in answer to "merge k sorted lists".
Syntax
import heapq
nums = [5, 1, 8, 3, 9]
heapq.nlargest(2, nums) # -> [9, 8], O(n log k)
heapq.nsmallest(2, nums) # -> [1, 3]
With key=
import heapq
from collections import Counter
points = [[1, 3], [-2, 2], [5, 8]]
heapq.nsmallest(2, points, key=lambda p: p[0] ** 2 + p[1] ** 2)
# -> [[-2, 2], [1, 3]], k closest to origin (LeetCode 973)
c = Counter([1, 1, 1, 2, 2, 3])
heapq.nlargest(2, c, key=c.get) # -> [1, 2], top-k frequent (LeetCode 347)
Which tool when
import heapq
nums, k = [5, 1, 8, 3, 9], 2
min(nums) # k == 1: O(n)
heapq.nsmallest(k, nums) # small k vs n: O(n log k)
sorted(nums)[:k] # k close to n: O(n log n), simplest
# Streaming / items arriving over time: keep your own size-k heap
merge sorted iterables
import heapq
a, b, c = [1, 4, 7], [2, 5], [3, 6, 9]
list(heapq.merge(a, b, c)) # -> [1, 2, 3, 4, 5, 6, 7, 9], O(N log k)
list(heapq.merge([5, 3], [4, 1], reverse=True)) # inputs sorted desc -> [5, 4, 3, 1]
list(heapq.merge(["bb", "a"], ["ccc"], key=len, reverse=True)) # -> ['ccc', 'bb', 'a']
Merge k sorted linked lists (LeetCode 23)
import heapq
class ListNode:
def __init__(self, val: int = 0, next: "ListNode | None" = None):
self.val, self.next = val, next
def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None:
pq = [(node.val, i, node) for i, node in enumerate(lists) if node]
heapq.heapify(pq) # i breaks ties, nodes never compared
dummy = tail = ListNode()
while pq:
_, i, node = heapq.heappop(pq)
tail.next = tail = node
if node.next:
heapq.heappush(pq, (node.next.val, i, node.next))
return dummy.next # O(N log k)
l = merge_k_lists([ListNode(1, ListNode(4)), ListNode(2, ListNode(3))])
out = []
while l:
out.append(l.val); l = l.next
out # -> [1, 2, 3, 4]