|
| 1 | +/*Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, |
| 2 | +and return an array of the non-overlapping intervals that cover all the intervals in the input. |
| 3 | +
|
| 4 | +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] |
| 5 | +Output: [[1,6],[8,10],[15,18]] |
| 6 | +Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. |
| 7 | +
|
| 8 | +
|
| 9 | +
|
| 10 | +Sorting takes O(n log(n)) and merging the intervals takes O(n). So, the resulting algorithm i.e. sorting, takes O(n log(n)). |
| 11 | +*/ |
| 12 | + |
| 13 | + |
| 14 | +class Solution { |
| 15 | + |
| 16 | + public int[][] merge(int[][] intervals) { |
| 17 | + if (intervals.length <= 1) |
| 18 | + return intervals; |
| 19 | + |
| 20 | + // Sort on th basis of ascending starting point |
| 21 | + Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0])); |
| 22 | + |
| 23 | + List<int[]> result = new ArrayList<>(); |
| 24 | + int[] newInterval = intervals[0]; |
| 25 | + result.add(newInterval); |
| 26 | + |
| 27 | + |
| 28 | + for (int[] interval : intervals) { |
| 29 | + if (interval[0] <= newInterval[1]) |
| 30 | + // Overlapping intervals, move the end if needed |
| 31 | + // overlap condition (update the end pointer) |
| 32 | + |
| 33 | + newInterval[1] = Math.max(newInterval[1], interval[1]); |
| 34 | + |
| 35 | + else { |
| 36 | + // Disjoint intervals, add the new interval to the list |
| 37 | + |
| 38 | + newInterval = interval; |
| 39 | + result.add(newInterval); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return result.toArray(new int[result.size()][]); |
| 44 | + } |
| 45 | +} |
0 commit comments