Merging Overlapping Intervals
After sorting by start time, compare the next start with the end of the accumulated interval.
Core Intuition & How It Works
Merging overlapping intervals sorts ranges by start time and sweeps once to combine any interval whose start is less than or equal to the current merged end. Sorting guarantees all overlapping partners appear adjacently.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n log n) |
| Space Complexity | O(n) |
| Topic Chapter | Chapter 3: Array & String Techniques |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Sort by start time, then either extend the last interval’s end via max(lastEnd, curEnd) or append a new disjoint interval.
Common Pitfalls & Edge Cases
Overwriting lastEnd with curEnd instead of max(lastEnd, curEnd), which breaks when one interval is completely nested inside another.
Real-World & Technical Interview Applications
Calendar availability, video timeline compaction, memory allocator block coalescing, and database range scans.