Merge Intervals in Java: Explanation & Practice

Merge overlapping intervals

Problem summary

Given a list of intervals, merge all overlapping intervals.

Starter code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[][] intervals = {{1,3}, {2,6}, {8,10}, {15,18}};
        
        // Merge overlapping intervals
        // Print: [1,6] [8,10] [15,18]
    }
}

Expected output and test cases

  • [1,3] and [2,6] merge
    [1,6] [8,10] [15,18]
  • All intervals overlap
    [1,5]

Hints

  1. Sort by start time
  2. Compare end of current with start of next
  3. Extend current interval if overlapping

Related Collections exercises

Practice all Collections exercises · Run this idea in the Java compiler