4. Linked Lists, Trees & Heaps
Binary Search Trees (BST) & Priority Queues (heapq)
Validate Binary Search Trees using min/max bounds and solve Top-K / streaming median / task scheduling problems in O(n log k) using Python's heapq min-heap.
- Validate BST ordering globally using lower/upper bounds rather than immediate child checks
- Use Python's heapq min-heap for O(log n) push/pop and O(1) peek
- Simulate a max-heap cleanly in Python by negating numeric priorities
Two ordered structures dominate priority scheduling and fast range lookups in technical interviews: Binary Search Trees (BSTs) and Priority Queues (heapq).
Why It Matters: Maintaining Order Dynamically
Suppose new scores arrive in a live stream and you repeatedly need the current Top-k largest scores (or the next highest-priority job):
- Re-sorting on every arrival: Calling
sorted(items)after each ofninsertions costsn × O(n log n)→O(n² log n)! - A Binary Heap (
heapq): Keeps only the smallest (or largest) element at index0inO(1)and inserts/removes inO(log n), solving Top-kovernitems inO(n log k)time andO(k)space!
Pattern 1: Binary Search Trees (Watch the Global Bounds Trap!)
In a valid BST, every node in node.left's entire subtree must be strictly < node.val, and every node in node.right's entire subtree must be strictly > node.val.
def is_valid_bst(node, low=float("-inf"), high=float("inf")) -> bool:
if not node:
return True
if not (low < node.val < high):
return False
return is_valid_bst(node.left, low, node.val) and is_valid_bst(node.right, node.val, high)Dry-Run Trace: Why Local Checks Fail on [5, 1, 6, 4, 8]
Consider root 5, left child 1, right child 6 with children (4, 8):
- Local check at
6:4 < 6 < 8looks valid! - Global bounds check:
is_valid_bst(5, -inf, +inf)→True, passes(5, +inf)to right child6.is_valid_bst(6, 5, +inf)→5 < 6 < +infisTrue, passes(5, 6)to left child4.is_valid_bst(4, 5, 6)→5 < 4 < 6isFalse! Caught immediately because4sits in the right subtree of5!
Pattern 2: Priority Queues with heapq
Push 6 into [4, 5]
[4, 5, 6] (len > 2)
heappop() evicts 4 → [5, 6]
heap[0] == 5 (2nd largest!)
Keep a min-heap capped at size k=2: whenever a larger item enters, heappop() evicts the smallest so heap[0] always holds the K-th largest!
Python's built-in heapq module turns a standard list into a min-heap (smallest element always sits at h[0]):
| Operation | Code | Time Complexity |
|---|---|---|
| Build heap from existing list | heapq.heapify(nums) | O(n) (faster than n pushes!) |
| Push element | heapq.heappush(h, x) | O(log n) |
| Pop smallest element | heapq.heappop(h) | O(log n) |
| Peek smallest element | h[0] | O(1) |
Top-k largest in stream | Min-heap capped at size k | O(n log k) time, O(k) space |
Step-by-Step Dry-Run: kth_largest([3, 2, 1, 5, 6, 4], k=2)
To find the 2nd largest, keep a min-heap of size 2—whenever size exceeds 2, heappop evicts the smallest so the 2 largest survivors remain!
Incoming x | Heap After heappush | len > 2? | Evicted (heappop) | Heap After Step |
|---|---|---|---|---|
3 | [3] | No | — | [3] |
2 | [2, 3] | No | — | [2, 3] |
1 | [1, 3, 2] | Yes | 1 | [2, 3] |
5 | [2, 3, 5] | Yes | 2 | [3, 5] |
6 | [3, 5, 6] | Yes | 3 | [5, 6] |
4 | [4, 6, 5] | Yes | 4 | [5, 6] |
At the end, min_heap[0] is 5—the exact 2nd largest element!
Edge Cases & Python Tuple Comparison Traps
- Empty heap: Calling
heapq.heappop([])or readingh[0]raisesIndexError—always checkif h:. - Simulating a Max-Heap: Push
-valand negate back on pop (-heapq.heappop(h)). - Tuple ties in
heapq: When pushing(priority, node_obj), if two items have equalpriority, Python tries to comparenode_obj < node_objand crashes withTypeError: '<' not supported between instances of 'Node' and 'Node'! Fix it by pushing a tie-breaker counter:(priority, tie_id, node_obj).
A heap only guarantees h[0] is the smallest element—h itself is NOT sorted! Never index h[-1] expecting the largest element or iterate for x in h: expecting sorted order. Pop repeatedly with heappop(h) when you need sorted output.
If all n items are already in a list, heapq.heapify(arr) rearranges the list in place in O(n) time using bottom-up sift-down, compared to O(n log n) for n individual heappush calls.
Try It Yourself in the Playground
Test is_valid_bst, kth_largest (min-heap of size k), and a Max-Heap Task Scheduler below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: How do you use Python's heapq (which is a min-heap) to behave as a max-heap for task priorities?
Quick Checkpoints
Why is checking only node.left.val < node.val < node.right.val insufficient to validate a Binary Search Tree?
What is the time complexity of finding the K-th largest element in a stream of n numbers using a min-heap capped at size k?
You build a heap from an existing list of n elements using heapq.heapify(arr). What is the time complexity?