MERGE INTERVALS PROGRAM IN JAVA

By | March 26, 2024

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].

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

public class MergeIntervals {
    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        List<int[]> merged = new ArrayList<>();
        for (int[] interval : intervals) {
            if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0]) {
                merged.add(interval);
            } else {
                merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
            }
        }
        return merged.toArray(new int[merged.size()][]);
    }

    public static void main(String[] args) {
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] result = merge(intervals);
        System.out.println(Arrays.deepToString(result));
    }
}

Explanation:

  • We sort the intervals based on the start time, which takes O(n log n) time complexity.
  • Then, we iterate through the sorted intervals once, which takes O(n) time complexity.
  • Within the iteration, the operations performed for merging the intervals are constant time operations.
  • So, the overall time complexity of the program is O(n log n), where n is the number of intervals.
  • The space complexity is O(n) to store the merged intervals.

Leave a Reply

Your email address will not be published. Required fields are marked *