← Back to DSA
#56

Merge Intervals

Merge Intervals solution for LeetCode 56, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.

Medium
ArraySortingIntervals
Solve on LeetCode ↗

Merge Intervals

Why it belongs on this sheet

Interval questions are common in placements, and this is the base template for all of them.

Pattern

Sort by start, merge by end

Approach

Sort intervals by start time. Keep the current merged interval and either extend it if the next interval overlaps or flush it into the answer if it does not.

Java solution

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
  public int[][] merge(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    List<int[]> merged = new ArrayList<>();

    int[] current = intervals[0];
    for (int i = 1; i < intervals.length; i++) {
      if (intervals[i][0] <= current[1]) {
        current[1] = Math.max(current[1], intervals[i][1]);
      } else {
        merged.add(current);
        current = intervals[i];
      }
    }

    merged.add(current);
    return merged.toArray(new int[merged.size()][]);
  }
}

Complexity

  • Time: O(n log n) because of sorting
  • Space: O(n) for the output list

Interview note

Say clearly why sorting by start is enough. That is the main reasoning checkpoint.

Dynamic Programming

7 DP Patterns > 100 LeetCode Questions

Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.

7 patternsProgress tracking
Read 7 patterns (5 min)