Article start
DSA Course: Interview Patterns and Problem Solving
Module 10: Sorting & Searching

Merge Intervals: Sort and Sweep Pattern

Merge overlapping intervals after sorting by start time.

May 29, 2026·26

Learning Outcome

After this lesson, you should be able to sort intervals by start and maintain one active merged interval.

Problem Statement

Given a list of intervals, merge all overlapping intervals and return the non-overlapping result.

InputOutputWhy
intervals = [[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]][1,3] overlaps [2,6], so they merge into [1,6].

Brute Force Approach

Repeatedly compare every interval with every other interval until no merges remain. This is slow and easy to get wrong.

Optimized Approach

Sort intervals by start. Sweep from left to right and merge into the last interval when starts overlap.

Exact Pseudocode

sort intervals by start
merged = []
for interval in intervals:
  if merged is empty or interval.start > merged.last.end:
    add interval to merged
  else:
    merged.last.end = max(merged.last.end, interval.end)
return merged

Reference Code

class Solution:
    def merge(self, intervals):
        intervals.sort(key=lambda x: x[0])
        merged = []

        for start, end in intervals:
            if not merged or start > merged[-1][1]:
                merged.append([start, end])
            else:
                merged[-1][1] = max(merged[-1][1], end)

        return merged

Sample Dry Run

StepStateResult
SortIntervals already sorted by startReady to sweep
[1,3]merged is emptyadd [1,3]
[2,6]2 <= 3merge to [1,6]
[8,10]8 > 6start new interval

Complexity

MeasureValueReason
TimeO(n log n)Sorting dominates the runtime.
SpaceO(n)The merged output can store all intervals.

Edge Cases

  • Touching intervals like [1,4] and [4,5] usually merge.
  • An empty interval list returns empty output.
  • Sorting by end time breaks the sweep invariant.

Interview Checklist

  • Sort by interval start.
  • Compare current start with last merged end.
  • Extend the last merged end with max end.

FAQs

Why sort first?

Sorting puts possible overlaps next to each other, so one left-to-right sweep is enough.

Why compare with the last merged interval?

After sorting, only the active last merged interval can overlap the current interval.

What is the core pattern?

Sort and sweep.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.