LeetCode 0056. Merge Intervals Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0056. Merge Intervals

Description

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.

 

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

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Example 3:

Input: intervals = [[4,7],[1,4]]
Output: [[1,7]]
Explanation: Intervals [1,4] and [4,7] are considered overlapping.

 

Constraints:

  • 1 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 104

Solutions

Solution 1: Sorting + One-pass Traversal

We can sort the intervals in ascending order by the left endpoint, and then traverse the intervals for merging operations.

The specific merging operation is as follows.

First, we add the first interval to the answer. Then, we consider each subsequent interval in turn:

  • If the right endpoint of the last interval in the answer array is less than the left endpoint of the current interval, it means that the two intervals will not overlap, so we can directly add the current interval to the end of the answer array;
  • Otherwise, it means that the two intervals overlap. We need to use the right endpoint of the current interval to update the right endpoint of the last interval in the answer array, setting it to the larger of the two.

Finally, we return the answer array.

The time complexity is O(n × log n), and the space complexity is O(log n). Here, n is the number of intervals.

PythonJavaC++GoTypeScriptRustC#JavaScriptKotlin
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort() ans = [] st, ed = intervals[0] for s, e in intervals[1:]: if ed < s: ans.append([st, ed]) st, ed = s, e else: ed = max(ed, e) ans.append([st, ed]) return ans(code-box)

Solution 2

PythonJavaC++GoTypeScriptC#
class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort() ans = [intervals[0]] for s, e in intervals[1:]: if ans[-1][1] < s: ans.append([s, e]) else: ans[-1][1] = max(ans[-1][1], e) return ans(code-box)

Solution 3

TypeScript
function merge(intervals: number[][]): number[][] { intervals.sort((a, b) => a[0] - b[0]); const n = intervals.length; const res = []; let i = 0; while (i < n) { let [l, r] = intervals[i]; i++; while (i < n && r >= intervals[i][0]) { r = Math.max(r, intervals[i][1]); i++; } res.push([l, r]); } return res; }(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !