Skip to content
CodeItRaw
Heaps & Priority Queues

Lesson 2/2

Finding the k-th largest element does not need the whole list sorted. Keep a heap no bigger than k: add each element, and when the heap grows past k throw out its smallest. At the end the heap holds the k largest, and the smallest of them, heap[0], is the k-th largest.

import heapq
heap = []
for v in values:
heapq.heappush(heap, v)
if len(heap) > k:
heapq.heappop(heap)
return heap[0]
It looks backwards and is right: to keep the largest you use a heap that throws out the smallest. The heap never grows past k, so each operation is log k; with a very long list and a small k that is clearly cheaper than sorting.

The second pattern: "always take the two smallest, join them, put the result back". Joining ropes at the lowest cost is like that: a rope joined early is counted again in every later join, so the short ones must be joined first. A sorted list does not help here, because the joined rope lands somewhere in the middle; a heap puts it in its place by itself.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Kth Largest

    Function

  2. 02

    Joining Ropes

    Function

  3. 03

    The k Smallest

    Code reading · Review the AI

If you would rather not wait for the order, every problem is open without locks: Problem list