Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Trees and hierarchy
EXPERIMENT 28 / 66

Next most important, please.

Schedule by priority without sorting the whole backlog after every insertion.

BY NAVAN SAMI◷ 7 MIN READCORESTRUCTURE

01 Model the idea

A min-heap keeps its smallest element at the root while maintaining a partial ordering among the rest. heapq operates on ordinary lists with push and pop operations that take logarithmic time. The underlying list is not completely sorted. For task scheduling, store tuples containing a priority and a deterministic tie-breaker.

THE THING THAT MUST STAY TRUE

Every parent is no greater than its children in the min-heap order.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
PUSH a priority and deterministic tie-breaker
REPEATEDLY remove the smallest available tuple

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

heaps.py
import heapq
queue = []
for order, (priority, name) in enumerate([(3, "Polish"), (1, "Fix"), (1, "Test")]):
    heapq.heappush(queue, (priority, order, name))
while queue:
    priority, _, name = heapq.heappop(queue)
    print(priority, name)
↳ EXPECTED OUTPUT
1 Fix
1 Test
3 Polish
  1. 1

    The smallest numeric priority is processed first. State that convention so callers do not assume larger numbers mean more urgency.

  2. 2

    The increasing order value breaks ties consistently and prevents Python from needing to compare arbitrary task objects.

  3. 3

    heapify builds a heap from an existing list in linear time. Do not mutate an item’s priority in place without repairing the heap; insert a revised entry and manage stale entries or use a suitable abstraction.

04 Count the cost

TIME

O(log n) push/pop; O(n) heapify

SPACE

O(n) heap storage

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Find the three smallest values without sorting the complete input explicitly.

Reveal one possible solution +
one_possible_solution.py
import heapq
print(heapq.nsmallest(3, [9, 1, 7, 2, 8, 3]))

06 Check your reasoning

QUICK SIGNAL CHECK

Is the heap’s entire backing list sorted?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.