Merge Intervals

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Merge Intervals

Approach

Sort intervals by start time. Initialize the result with the first interval. For each subsequent interval, check if it overlaps with the last merged interval (prev.end >= curr.start). If so, extend the previous interval. Otherwise, add the current interval as new.

Complexity Analysis

Time
O(n log n)
Space
O(n)

Pattern

Sort + Linear Scan

Why It Works

Sorting by start time ensures we only need to compare each interval with the last merged one. If the current interval starts before or at the previous end, they overlap. Taking the max of ends handles contained intervals correctly.

Updated Feb 2026