|
| 1 | +# Merge Intervals |
| 2 | + |
| 3 | +Page on leetcode: https://leetcode.com/problems/merge-intervals/ |
| 4 | + |
| 5 | +## Problem Statement |
| 6 | + |
| 7 | +Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. |
| 8 | + |
| 9 | +### Constraints |
| 10 | + |
| 11 | +- 1 <= intervals.length <= 104 |
| 12 | +- intervals[i].length == 2 |
| 13 | +- 0 <= starti <= endi <= 104 |
| 14 | + |
| 15 | +### Example |
| 16 | + |
| 17 | +``` |
| 18 | +Input: intervals = [[1,3],[2,6],[8,10],[15,18]] |
| 19 | +Output: [[1,6],[8,10],[15,18]] |
| 20 | +Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. |
| 21 | +``` |
| 22 | + |
| 23 | +``` |
| 24 | +Input: intervals = [[1,4],[4,5]] |
| 25 | +Output: [[1,5]] |
| 26 | +Explanation: Intervals [1,4] and [4,5] are considered overlapping. |
| 27 | +``` |
| 28 | + |
| 29 | +## Solution |
| 30 | + |
| 31 | +- Is intervals always sorted? We will assume yes for now |
| 32 | + |
| 33 | +### Pseudocode |
| 34 | + |
| 35 | +1. Create empty array result |
| 36 | +2. Create curInterval and set to intervals[0] |
| 37 | +3. Iterate thru intervals |
| 38 | +4. ith interval [0] is less than or equal currInterval[1], set curr[0] to min of ith and curr and set curr[1] to max of ith and curr. |
| 39 | +5. Else push curr to result |
| 40 | +6. Set curr equal to ith |
| 41 | +7. Push curr to result |
| 42 | +8. Return result |
| 43 | + |
| 44 | +### Initial Solution |
| 45 | + |
| 46 | +This solution has a time complexity of O(nlogn) due to sorting and a space complexity of O(n) due returning a result array. You can see an explanation of the approach to this problem here: https://www.youtube.com/watch?v=44H3cEC2fFM |
| 47 | + |
| 48 | +```javascript |
| 49 | +const merge = function (intervals) { |
| 50 | + // In order for below to work need a sorted array. Sort lowest to highest by the 0-index of the interval |
| 51 | + intervals.sort((a, b) => a[0] - b[0]); |
| 52 | + |
| 53 | + const result = []; |
| 54 | + let curr = intervals[0]; |
| 55 | + |
| 56 | + for (let i = 1; i < intervals.length; i++) { |
| 57 | + if (intervals[i][0] <= curr[1]) { |
| 58 | + // If there is overlap, update current interval to span the overlapping intervals |
| 59 | + curr[0] = Math.min(curr[0], intervals[i][0]); |
| 60 | + curr[1] = Math.max(curr[1], intervals[i][1]); |
| 61 | + } else { |
| 62 | + // If no overlap then add current interval to the result and update current interval to the just checked interval |
| 63 | + result.push(curr); |
| 64 | + curr = intervals[i]; |
| 65 | + } |
| 66 | + } |
| 67 | + result.push(curr); |
| 68 | + |
| 69 | + return result; |
| 70 | +}; |
| 71 | +``` |
0 commit comments