Section 3: Heap, Intervals, and Greedy
This section covers three patterns that share a common theme: making the best decision at each step. Heaps give you the best candidate right now (smallest or largest) without sorting the entire collection. Interval problems ask you to reason about overlapping or conflicting time ranges, and the key is always sorting first. Greedy algorithms prove that choosing the locally optimal option at each step leads to the globally optimal result.
These three patterns are grouped together because they frequently combine. Interval problems often use sorting plus a greedy selection strategy. Heap problems often use a greedy “take the best next candidate” approach. Understanding how they interact is as important as knowing each pattern individually.
What We’ll Cover:
Where This Appears in Interviews:
| Company Type | How This Section Appears |
|---|---|
| FAANG / Big Tech | Top K Frequent Elements, Merge K Sorted Lists, and Merge Intervals are top-20 most-asked |
| Mid-size companies | Meeting Rooms and interval scheduling are common phone screen questions |
| Startups | Priority queue usage for task scheduling, event processing |
| Online assessments | Interval problems and Top K are common timed questions |
Core Idea for This Section: Use heaps when you repeatedly need the best next candidate. Use interval sorting when the problem is about overlap. Use greedy when a local choice can be justified globally.
What a Heap Is: A heap is a data structure that gives you the smallest (min heap) or largest (max heap) element in O(1) and supports insertion and removal in O(log n). It is the right tool when you need repeated access to the extreme value in a changing collection.
Python’s heapq Module:
Python only provides a min heap. For a max heap, negate the values.
import heapq
min_heap = []
heapq.heappush(min_heap, 5)
heapq.heappush(min_heap, 2)
heapq.heappush(min_heap, 8)
smallest = heapq.heappop(min_heap)
peek = min_heap[0]