šŸ”— LeetCode

Merge Intervals

MediumgreedyGoogleAmazon

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals.

Examples

Input:intervals = [[1,3],[2,6],[8,10],[15,18]]
Output:[[1,6],[8,10],[15,18]]

Constraints

    šŸ’” Hints

    Hint 1

    Sort intervals by their start times first.

    Algorithm Complexity

    Official asymptotic Big-O runtime and auxiliary memory analysis

    Linearithmic
    Algorithmic Approach

    Sort intervals by start time. Iterate through them, merging overlapping intervals into the current interval or starting a new interval.

    Time ComplexityO(N log N)
    Why:

    Sorting intervals by start time takes O(N log N), followed by a single linear O(N) sweep to merge overlapping pairs.

    Space ComplexityO(1)
    Why:

    The merged intervals list stores up to N non-overlapping output intervals.

    Big-O Growth CurveLinearithmic (O(N log N))
    Scales efficiently for sorting and divide-and-conquer algorithms.

    šŸ” Dry Run

    Solutionā± O(N log N) | šŸ’¾ O(1)

    Intervals

    [1, 3]
    [2, 6]
    [8, 10]
    [15, 18]
    -1
    2
    5
    8
    11
    14
    17
    20