Skip to main content

Merge Overlapping Intervals in Java and Python

Merge overlapping closed intervals with a sort-and-scan algorithm. See how Java and Python handle touching endpoints, nesting, and empty input.

Problem and input contract

Given pairs (start, end) with start ≤ end, return sorted, disjoint closed intervals with the same union. The functions preserve the input.

[(5, 7), (1, 3), (3, 6)] gives [(1, 7)]. [(1, 9), (2, 4), (12, 12)] gives [(1, 9), (12, 12)]. Empty input gives an empty result.

Worked example

[(5, 7), (1, 3), (3, 6)] merges to [(1, 7)].

After sorting, process (1, 3) first. The next interval starts at 3, so it touches the first and extends it to (1, 6). The last interval starts at 5 and extends the end to 7.

How the solution works

Sorting by start means the last merged interval is the only candidate for overlap with the next input interval. Using max preserves the existing end when the new interval is contained.

These are closed intervals, so equality counts as overlap. Sorting by start means a gap closes off all earlier merged intervals. The Java implementation copies arrays before modifying them.

Python solution

def merge_intervals(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            previous_start, previous_end = merged[-1]
            merged[-1] = (previous_start, max(previous_end, end))
        else:
            merged.append((start, end))
    return merged

Java solution

import java.util.*;
class Solution {
    static List<int[]> mergeIntervals(int[][] intervals) {
        int[][] sorted = intervals.clone();
        Arrays.sort(sorted, Comparator.comparingInt(pair -> pair[0]));
        List<int[]> merged = new ArrayList<>();
        for (int[] pair : sorted) {
            int[] last = merged.isEmpty() ? null : merged.get(merged.size() - 1);
            if (last != null && pair[0] <= last[1]) {
                last[1] = Math.max(last[1], pair[1]);
            } else {
                merged.add(pair.clone());
            }
        }
        return merged;
    }
}

Approaches and complexity

Checking every pair for overlap can take quadratic work before accounting for repeated merges. Sorting the starts brings intervals that can contribute to the same output segment together. Sorting takes O(n log n) worst-case time and the scan takes O(n). The sorted copy and sort workspace use O(n) auxiliary space, plus the output. With already sorted input, the scan alone is linear.

Approach comparison
ApproachTimeAuxiliary spaceAdvantageLimitationUse case
Sort and scanO(n log n)O(n)Handles unsorted inputNeeds sortingGeneral input
Scan sorted intervalsO(n)O(1) excluding outputLinear traversalRequires sorted startsInput already sorted

Common mistakes and interview follow-up

Use start ≤ lastEnd for closed intervals. Keep the larger endpoint so a nested interval cannot shrink the union. Once the next start exceeds the current end, all later starts lie beyond that end.

Related practice: Find the First Occurrence with Binary Search.

Comments

Popular posts from this blog

Minimum Window Substring: Efficient Algorithm for Finding the Shortest Substring

The Minimum Window Substring problem is a classic string manipulation challenge that tests our algorithmic skills. In this blog, we will explore an efficient solution to find the minimum window substring in a given string. We will provide implementation examples in both Java and Python, enabling you to grasp the concepts and apply them to your own coding projects.   Understanding the Problem: Given a string and a target pattern, our objective is to find the minimum window substring in the given string that contains all the characters of the target pattern. The minimum window substring refers to the shortest possible substring that satisfies this condition.   Approach: To solve the Minimum Window Substring problem, we can use the sliding window technique. This approach involves maintaining a window of characters in the string and adjusting its size based on certain conditions. The key steps of the algorithm are as follows: Create two pointers, left and right, to define the windo...

Longest Palindromic Substring: Explained with Java and Python Code

The Longest Palindromic Substring problem is a classic challenge in the realm of string manipulation. In this blog, we will delve into the intricacies of finding the longest palindromic substring in a given string. Through a step-by-step approach and illustrative examples, you will gain a comprehensive understanding of the problem and learn how to solve it efficiently.   Understanding the Problem: A palindrome is a string that reads the same forward and backward. The Longest Palindromic Substring problem requires finding the longest substring within a given string that is also a palindrome. Our goal is to determine the length of this substring and return the substring itself.   Approach: To solve the Longest Palindromic Substring problem, we can employ a dynamic programming approach or use the expanding around center technique. Here, we will explore the dynamic programming approach. Create a boolean table, dp, of size [n][n] (where n is the length of the input string) to store ...