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
- Sort by start time
- Compare end of current with start of next
- Extend current interval if overlapping
Related Collections exercises
- Practice Sliding Window Maximum in Java
- Practice Top K Frequent Elements in Java
- Practice Task Scheduler in Java
Practice all Collections exercises · Run this idea in the Java compiler