Build a Min-Heap and Schedule Tasks by Priority
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Construct a working min-heap from scratch, then apply it to schedule dependent tasks in lexicographic order while detecting cycles.
You will solve two connected problems in a single session.
Part 1: Custom Min-Heap Implementation
Build a MinHeap class that maintains elements in min-heap order. Your implementation must support:
push(x): Add elementxto the heappop(): Remove and return the minimum elementpeek(): Return the minimum element without removing it__len__(): Return the count of elements currently in the heap- A constructor accepting an optional iterable of initial values, building the heap in O(n) time
Your heap should handle comparable values like integers or tuples. When the heap is empty, pop() and peek() should raise IndexError.
Requirements:
- Implement the heap using a list-based binary tree representation
- Do not use
heapq,queue.PriorityQueue, or any other built-in priority queue - Do not sort the entire collection on every operation
- The constructor must run in linear time when given initial values
Part 2: Task Scheduling with Dependencies
You have n tasks numbered from 0 to n - 1. Some tasks depend on others: you are given a list of dependency pairs [task, required], where required must be finished before task can start.
Complete all tasks one at a time. When multiple tasks are ready (all their dependencies are satisfied), always choose the one with the smallest number. Return the completion order as a list of task numbers.
If the dependencies form a cycle that prevents completing all tasks, return an empty list.
You must use the MinHeap class from Part 1 to determine which task to complete next.
Example:
- With
n = 3and dependencies[[0, 1]], task1must finish before task0 - Tasks
1and2start ready (no dependencies) - Choose task
1(smaller number), which unlocks task0 - Task
0is now the smallest ready task - Finally complete task
2 - Result:
[1, 0, 2]
Constraints
1 ≤ n ≤ 20000 ≤ dependencies.length ≤ 5000- Each dependency pair
[a, b]satisfies0 ≤ a, b < n - The input may contain duplicate dependency pairs
- A task will not list itself as its own dependency in valid test cases
Examples
Example 1
Input: schedule_tasks(3, [[0, 1]])
Output: [1, 0, 2]
Example 2
Input: schedule_tasks(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
Output: [0, 1, 2, 3]
Example 3
Input: schedule_tasks(2, [[0, 1], [1, 0]])
Output: []
Hints
Hint 1
For the heap: remember that in array index i, the children are at 2i+1 and 2i+2, and the parent is at (i-1)//2
Hint 2
Linear-time heap construction works by starting from the last non-leaf node and sifting down, rather than inserting elements one by one
Hint 3
For task scheduling: track how many dependencies each task has remaining, and use the heap to always pick the smallest task number among those with zero remaining dependencies
Hint 4
If you finish fewer than n tasks, some tasks were blocked by circular dependencies
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Part 1: Min-Heap Implementation
A binary min-heap stores elements in an array where each parent is smaller than its children. For element at index i:
- Parent is at index
(i - 1) // 2 - Left child is at index
2 * i + 1 - Right child is at index
2 * i + 2
Operations:
- Push: Append the new value to the end, then bubble it up by swapping with its parent until the parent is smaller or we reach the root
- Pop: Save the root (minimum), move the last element to the root, then sift it down by repeatedly swapping with the smaller child until both children are larger or we reach a leaf
- Peek: Simply return the root element
- Construction: Given n initial values, we could push each individually in O(n log n), but it's faster to place all values in the array and then sift down from the last non-leaf node backward to the root. This runs in O(n) because nodes near the bottom do less work.
Part 2: Task Scheduling
This is topological sorting with a twist: when multiple tasks are ready, we must pick the smallest number. The standard approach uses:
- Build an adjacency list showing which tasks each task unlocks
- Count incoming dependencies for each task
- Initialize a heap with all tasks having zero dependencies
- Repeatedly pop the smallest ready task, add it to the result, decrement dependency counts of tasks it unlocks, and push newly ready tasks to the heap
- If we complete fewer than n tasks, a cycle prevented finishing some tasks
The heap ensures we always process the smallest-numbered ready task, making the output deterministic.
Complexity:
- Heap push/pop: O(log k) where k is the heap size
- Heap construction from n items: O(n)
- Task scheduling: O((n + m) log n) where m is the number of dependency edges, since we perform heap operations up to n times with heap size up to n
- Space: O(n + m) for the adjacency list and dependency counts
Solution
from typing import List
class MinHeap:
def __init__(self, values=None):
self.data = list(values) if values is not None else []
for i in range(len(self.data) // 2 - 1, -1, -1):
self._sift_down(i)
def __len__(self):
return len(self.data)
def push(self, value):
self.data.append(value)
i = len(self.data) - 1
while i > 0:
parent = (i - 1) // 2
if self.data[parent] <= self.data[i]:
break
self.data[parent], self.data[i] = self.data[i], self.data[parent]
i = parent
def peek(self):
if not self.data:
raise IndexError("peek from empty heap")
return self.data[0]
def pop(self):
if not self.data:
raise IndexError("pop from empty heap")
smallest = self.data[0]
last = self.data.pop()
if self.data:
self.data[0] = last
self._sift_down(0)
return smallest
def _sift_down(self, i):
n = len(self.data)
while True:
left = 2 * i + 1
right = left + 1
smallest = i
if left < n and self.data[left] < self.data[smallest]:
smallest = left
if right < n and self.data[right] < self.data[smallest]:
smallest = right
if smallest == i:
return
self.data[i], self.data[smallest] = self.data[smallest], self.data[i]
i = smallest
def schedule_tasks(n, dependencies):
adjacency = [[] for _ in range(n)]
incoming_count = [0] * n
processed = set()
for task, required in dependencies:
edge_key = (required, task)
if edge_key not in processed:
processed.add(edge_key)
adjacency[required].append(task)
incoming_count[task] += 1
ready_heap = MinHeap(i for i in range(n) if incoming_count[i] == 0)
completion_order = []
while ready_heap:
current_task = ready_heap.pop()
completion_order.append(current_task)
for dependent_task in adjacency[current_task]:
incoming_count[dependent_task] -= 1
if incoming_count[dependent_task] == 0:
ready_heap.push(dependent_task)
return completion_order if len(completion_order) == n else []