Skip to content
CodeItRaw
Path

Always grabbing the smallest or largest fast: heapq, two heaps and priorities.

Key ideas

  • heapq hands you the smallest in O(log n): heappush, heappop, heap[0].
  • For the largest, push negated values.
  • A heap of size k answers "the k largest" over a stream without growing memory.

Pattern

import heapq
heap = []
heapq.heappush(heap, (priority, item))
priority, item = heapq.heappop(heap)  # the smallest priority
smallest = heap[0]  # peek without removing

Finish these first:Stacks & Queues

Lessons

Each lesson explains one idea from zero and ends with a few tasks. Lessons open in order; the explanation can be read at any time.

  1. 01

    The heap: the smallest always at hand

    0/2 tasks

  2. 02

    The k largest, and "always the two smallest"

    0/3 tasks

Boss

  • 03

    Running Median

    Function

  • The boss opens when every lesson of the topic is finished. Solve it too and the topic is complete, and the topics after it open.