Search lands in PR-5.1 (Pagefind).

Explanation Intermediate

Chapter 1 Updated

Intervals — Fundamentals

Core mental models, sorting tricks, and overlap detection logic behind every interval problem.

  • Full 12m
  • Revision 3m
  • Flow 2m

What is an Interval?

An interval [start, end] represents a continuous range on some axis. In interviews, intervals model three kinds of domains:

DomainExampleTypical problem
TimeMeetings, cron jobs, booking windowsMeeting Rooms, Calendar
SpaceX-coordinates of balloons or segmentsBurst Balloons, Skyline
NumericRanges on the integer lineData Stream, Range Module

Whatever the domain, the underlying algebra is the same — two numbers defining a range, and a question about how that range relates to others.

The four flavors of interval notation

Interval notation
Closed     [a, b]   → includes both endpoints
Open       (a, b)   → excludes both endpoints
Half-open  [a, b)   → includes a, excludes b    ← most common in real systems
Half-open  (a, b]   → excludes a, includes b

The universal overlap formula

Two intervals [a1, a2] and [b1, b2] overlap if and only if:

The one formula you must memorize
            max(a1, b1)  ≤  min(a2, b2)
 
If true:
    Intersection = [ max(a1, b1), min(a2, b2) ]
    Union        = [ min(a1, b1), max(a2, b2) ]
 
If false:
    Gap          = [ min(a2, b2), max(a1, b1) ]

The 6 Interval Relationships

Every pair of intervals falls into exactly one of these six categories. Understanding them visually is the shortcut to writing clean, bug-free code.

① A entirely before B

  A:  ■■■■■
  B:                ■■■■■
      ─────┬────┬───┬────┬─────→
          A.s  A.e B.s  B.e
ConditionA.end < B.start
Overlap?No
Mental modelA finishes before B even begins.

② B entirely before A

  A:                ■■■■■
  B:  ■■■■■
      ─────┬────┬───┬────┬─────→
          B.s  B.e A.s  A.e
ConditionB.end < A.start
Overlap?No — mirror of ①.
After sortingImpossible — A always starts ≤ B.

③ Partial overlap — A starts first

  A:  ■■■■■■■■■
  B:        ■■■■■■■■■
            ▓▓▓▓▓  ← intersection
      ───┬────┬────┬────┬─────→
         A.s  B.s  A.e  B.e
ConditionA.start ≤ B.start AND A.end ≥ B.start AND A.end ≤ B.end
Merged[A.start, B.end]
Intersection[B.start, A.end]

④ Partial overlap — B starts first

  A:        ■■■■■■■■■
  B:  ■■■■■■■■■
            ▓▓▓▓▓  ← intersection
      ───┬────┬────┬────┬─────→
         B.s  A.s  B.e  A.e
ConditionB.start ≤ A.start AND B.end ≥ A.start AND B.end ≤ A.end
Merged[B.start, A.end]
After sortingImpossible — same reason as ②.

⑤ A fully contains B

  A:  ■■■■■■■■■■■■■■■
  B:       ■■■■■■■
      ───┬─────────────┬─────→
         A.s  B.s B.e  A.e
ConditionA.start ≤ B.start AND A.end ≥ B.end
Merged[A.start, A.end] (A already covers B)
TrapRemember to write end = max(A.end, B.end) — it handles this naturally.

⑥ B fully contains A

  A:       ■■■■■■■
  B:  ■■■■■■■■■■■■■■■
      ───┬─────────────┬─────→
         B.s  A.s A.e  B.e
ConditionB.start ≤ A.start AND B.end ≥ A.end
Merged[B.start, B.end]
After sortingBecomes: A.start = B.start but B.end > A.end.

Six cases collapse to three

Mental model — the timeline ruler

Picture intervals as blocks laid out on a ruler. Sorting aligns them left-to-right. Walk right; for each new block ask one question:

“Does it touch or overlap the last block I placed?”

If yes → extend. If no → start a new block. That single model solves Merge Intervals, Employee Free Time, and several other patterns.

Sorting Strategies

The single most important decision in any interval problem is how to sort. The wrong sort order = the wrong answer.

StrategyKeyUse it forProblems
Sort by startkey=x[0]Merging, inserting, intersections, conflict detection#56, #57, #252, #253, #759, #986
Sort by endkey=x[1]Greedy selection — max non-overlapping, min removals, min arrows#435, #452, Activity Selection
Start ↑, then end ↓key=(x[0], -x[1])Remove Covered Intervals — process largest span first at each start#1288
Event-based (sweep)key=(x[0], x[1])Counting active intervals at any point, peak usage, skyline#253 alt, #732, #1094, #218

The 6 Common Approaches

Pattern recognition comes from knowing the toolkit. Nearly every interval problem you’ll see reduces to one of these six techniques.

#ApproachWhen to reach for it
1Sort + linear scanMaintain a “last” interval, compare, merge or start fresh. Solves ~50% of all interval problems.
2Sweep line (events)Decompose into start/end events, sort, sweep, keep a running counter. Answers “how many overlap at point X?“
3Greedy selectionSort by end, greedily pick the earliest-finishing interval. For optimisation — max kept, min removals, min resources.
4Priority queue (heap)Track active intervals by end time in a min-heap. Answers “is any room free?” for resource allocation.
5Two pointersTwo pre-sorted interval lists — advance the pointer whose interval ends first. Key for intersection problems.
6Difference arrayBounded-integer coordinates — O(1) range updates via diff[l] += v; diff[r+1] -= v, then prefix sum to recover values.

Pattern recognition cheat sheet

Universal Edge Cases

Before writing a single line of code, run through this checklist:

#ScenarioUsual handling
1Empty inputReturn [] / 0 / true — match the problem’s identity element
2Single intervalTrivial base case — return as-is
3All intervals identicalThey all merge into one
4No overlaps at allOutput equals input
5One giant interval covering everythingEverything merges into it
6Touching endpoints [1,2] & [2,3]Overlap? Depends on closed vs. half-open — clarify
7Zero-length [5,5]Valid point-interval or degenerate — confirm
8Negative coordinatesMake sure your math doesn’t assume positives
9Very large valuesWatch for start + end overflow on signed 32-bit

The 22 Pattern Map

Every interval problem in this season maps to one of six core techniques. Use this table as your index — the first 11 are the FAANG core, the next 11 are advanced extensions.

Core patterns (1–11)

#PatternLC #Sort byApproach
1Merge Intervals#56StartSort + linear scan
2Insert Interval#57pre-sortedThree-phase sweep
3Meeting Rooms I#252StartConsecutive pair check
4Meeting Rooms II#253Start / eventsMin-heap or sweep line
5Non-Overlapping Intervals#435EndGreedy selection
6Interval List Intersections#986pre-sortedTwo pointers
7Employee Free Time#759StartMerge + find gaps
8Remove Interval#1272pre-sortedSingle pass + remnants
9My Calendar I#729Overlap check per booking
10My Calendar II#731Two-layer tracking
11Data Stream as Disjoint Intervals#352maintainedBinary search + merge

Advanced patterns (12–22)

#PatternLC #Sort byApproach
12Sweep Line TemplateEvents+1 / −1 decomposition
13Min Arrows to Burst Balloons#452EndGreedy group counting
14My Calendar III#732EventsDelta timeline / TreeMap
15Car Pooling#1094EventsSweep or difference array
16Range Module#715maintainedInsert + Remove composed
17Meeting Rooms III#2402StartTwo heaps (avail + busy)
18Difference Array#1109O(1) range update + prefix sum
19The Skyline Problem#218EventsSweep + max-heap
20Rectangle Area II#850Events2-D sweep + merged y-coverage
21Interval Tree TemplateMedianStatic BST of intervals
22Task Scheduler#621FrequencyClosed-form math on counts

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.