Merge Intervals Problem Solving Tutorial: A Complete Comparison of 3 Solutions | LeetCode 56 Best Practice

Merge Intervals Problem Solving Tutorial Diagram | LeetCode 56

This article provides a complete breakdown of the solution to LeetCode problem 56 Merge Intervals: from the problem-solving approach and algorithm steps to time and space complexity, and it also summarizes boundary cases and compares three solutions to help you understand Merge Intervals in one go.

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given an array of intervals where intervals[i] = [start i , end i ], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Constraints:

  • 1 <= intervals.length <= 10 4
  • intervals[i].length == 2
  • 0 <= start i <= end i <= 10 4

Python

				
					# time complexity: O(nlogn) # space complexity: O(n) from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals. sort() mergeResult = [intervals[0]] for interval in intervals: if mergeResult[-1][1] < interval[0]: mergeResult.append(interval) else: mergeResult[-1][1] = max( mergeResult[-1][1], interval[1]) return mergeResult intervals = [[1, 3], [2, 6], [8, 10], [15, 18]] print(Solution().merge (intervals)) intervals = [[1, 4], [4, 5]] print(Solution().merge(intervals)) intervals = [[1, 4], [2, 3]] print(Solution() .merge(intervals)) intervals = [[1, 4], [1, 4]] print(Solution().merge(intervals))
				
			

Merge Intervals Problem-Solving Approach

The prerequisite for merging intervals is to sort them first. After sorting them from smallest to largest starting point, we only need to push forward using the "currently accumulating interval": if the starting point of the next interval does not exceed the ending point of the current interval, it means that the two overlap, and the maximum value of the ending point is taken to extend it; otherwise, the current interval is included in the answer, and a new interval is used to continue.

Merge Intervals Algorithm Steps

  1. Sort all intervals in ascending order of their starting points.
  2. Set the first interval as current and put it into the result array.
  3. Visit the remaining intervals: if interval[0] <= current[1], representing overlap, let current[1] = max(current[1], interval[1]).
  4. Otherwise, set the interval to the new current and add the result, then return the result array after the process is complete.

Merge Intervals Complexity Analysis

projectComplexity
Time complexityO(n log n)
Space complexityO(n)

Sorting takes O(n log n), merging only requires one linear scan, and the overall process is dominated by sorting. In the worst case, the resulting array will store n intervals, with a space of O(n) (if the output is ignored and it can be modified in place, the extra space can be regarded as O(1)).

Boundary cases and common errors of Merge Intervals

  • Whether adjacent but non-overlapping intervals (e.g., [1,2] and [3,4]) should be merged depends on the problem definition; in this problem, they should not be merged.
  • If there is only one interval, send it back directly.
  • The endpoint of the extension must be set to the maximum value, because the later interval may be completely contained within the earlier one.
  • When sorting, it is sufficient to compare only the starting point; comparing the ending point does not affect the correctness.

Comparison of other solutions for Merge Intervals

solutiontimespaceillustrate
Pairwise comparisons were repeatedly performed and merged until a stable state was reached.O(n²)O(n)No sorting required, but inefficient
Process with scan lines (event points)O(n log n)O(n)Suitable for extending to interval coverage problems
Sorting + Linear MergingO(n log n)O(n)This article adopts