2Brute2Best
🔥0
03

Intersection of two lists (Intervals Sub-pattern)

Two (or more) sorted lists of intervals. Walk them together with two pointers; the overlap of the current pair is [max start, min end]; advance whichever ends first.

Signals in the problem statement
  • ›

    "intersection of two interval lists"

  • ›

    "earliest time slot that works for both people"

  • ›

    "common free time of all employees"

What makes it different

Interval List Intersections outputs every non-empty overlap. Meeting Scheduler isn't sorted — sort both first — and stops at the first overlap at least duration long. Employee Free Time looks at many lists: merge all the busy intervals (flatten + sort, or a heap over the lists) and report the gaps between them.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Interval List Intersections
    Basic Anchor·LeetCode #986
    Medium
  2. 2
    Meeting Scheduler
    Slight Variation·LeetCode #1229 Premium
    Medium
  3. 3
    Employee Free Time
    Pattern Transfer·LeetCode #759 Premium
    Hard

Template

two-lists-template.cpp
// Interval List Intersections: both lists sorted and disjoint, intervals closed.
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
    vector<vector<int>> res;
    int i = 0, j = 0;
    while (i < (int)A.size() && j < (int)B.size()) {
        int lo = max(A[i][0], B[j][0]);
        int hi = min(A[i][1], B[j][1]);
        if (lo <= hi) res.push_back({lo, hi});        // non-empty overlap
        if (A[i][1] < B[j][1]) i++;                   // advance whoever ends first
        else j++;
    }
    return res;
}
Remember this · Intervals
Trigger
Input is [start, end] pairs; overlap, merge, insert, meeting rooms, free time, minimum removals.
Think
After sorting, do I only ever need to compare against the most recent interval?
Key question
Sort by start or by end — which one makes the greedy choice obvious?