Merge Intervals
Sort intervals by start time, then sweep and merge overlapping ones.
What is this pattern?
Interval problems become straightforward after sorting by start time. You then do a single pass: if the current interval overlaps the last merged one, extend it; otherwise push it as a new merged interval. The same sort-then-sweep idea applies to insertion, meeting room, and overlap counting problems.
When to use it
- Given a list of intervals, find overlaps or merge them
- Scheduling / meeting room problems
- Inserting a new interval into a sorted list
- Finding minimum number of groups/rooms to cover all intervals
Key Insight
Two intervals [a,b] and [c,d] overlap if and only if c ≤ b (after sorting by start). The merged interval is [a, max(b, d)]. Always sort first — the sweep only works in order.
Pro Content
The Java template and practice problems for this pattern are part of the Pro plan. Upgrade to unlock all patterns, 500+ problems, and Aria code reviews.
From ₹3,999 for a year · one-time, no auto-renewal