LeetCode 56: Merge Intervals — Python Solution

Solve LeetCode 56: Merge Intervals in Python with a sorted sweep approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

DifficultyMedium
TopicIntervals
Reusable patternsorted sweep
ComplexityO(n log n) time and O(n) output space

What the problem is testing

Sort by start time and either extend the last merged interval or append a new disjoint interval.

Algorithm

  1. Sort by start time and either extend the last merged interval or append a new disjoint interval.
  2. Maintain this invariant: The output is sorted, disjoint, and exactly covers every processed interval.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

class Solution:
    def merge(self, intervals):
        intervals.sort(key=lambda pair: pair[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

Why this is correct

The proof follows the maintained state: The output is sorted, disjoint, and exactly covers every processed interval. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

O(n log n) time and O(n) output space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.

Edge cases

Touching endpoints overlap under the problem definition.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


Browse the searchable 100 LeetCode Python Solutions hub. Previous: 228. Summary Ranges · Next: 57. Insert Interval