SLIDE 45: Section Intro, Heap, Intervals, and Greedy

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:

  1. Min heap and max heap fundamentals
  2. Top K pattern
  3. K-way merge pattern
  4. Interval sorting and overlap detection
  5. Greedy algorithms and correctness proofs
  6. Decision framework: heap vs sort vs greedy

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.


SLIDE 46: Min Heap and Max Heap Fundamentals

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]