DEV Community

Crack Tech
Crack Tech

Posted on

Merge Intervals in 15 Seconds

Merge Intervals looks messy until you sort by start time.

After sorting, keep one current block and scan left to right:

  • If the next interval starts before the current block ends, stretch the block.
  • Use max() for the new end, because the next interval may be fully inside the current block.
  • If there is a gap, start a new block.

The tricky case is [16,17] inside [15,18]: the merged end stays 18, not 17.

intervals.sort()

merged = []
for start, end in intervals:
    if merged and start <= merged[-1][1]:
        merged[-1][1] = max(merged[-1][1], end)
    else:
        merged.append([start, end])
Enter fullscreen mode Exit fullscreen mode

Time complexity: O(n log n) — the sort is the main cost.

Video: https://youtube.com/shorts/UMiMXzm7cvM

Question for you: in this problem, would you sort by start or by end?

Follow Crack Tech for Day 2: Interval Intersection.

Mentorship: https://cracktech.app

Top comments (0)