Skip to content

Commit 98df690

Browse files
committed
Add merge-intervals solution
1 parent 51181ff commit 98df690

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

merge-intervals/Jeehay28.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// 🚀 My own approach!
2+
// ✅ Time Complexity: O(n log n), where n is the number of intervals
3+
// ✅ Space Complexity: O(n) (due to the stack storage)
4+
5+
/**
6+
* @param {number[][]} intervals
7+
* @return {number[][]}
8+
*/
9+
var merge = function (intervals) {
10+
intervals.sort((a, b) => a[0] - b[0]);
11+
// Sorting takes O(n log n) time, where n is the number of intervals.
12+
// JavaScript's sort() is O(1) (in-place) for sorting in most cases.
13+
14+
let start = intervals[0][0];
15+
let end = intervals[0][1];
16+
let stack = [intervals[0]]; // O(n) additional space usage.
17+
18+
for (const [s, e] of intervals) {
19+
// This takes O(n) time.
20+
const [prevStart, prevEnd] = stack[stack.length - 1];
21+
22+
if (prevStart <= s && s <= prevEnd) {
23+
start = Math.min(s, start);
24+
end = Math.max(e, end);
25+
stack.pop();
26+
} else {
27+
start = s;
28+
end = e;
29+
}
30+
stack.push([start, end]);
31+
}
32+
return stack;
33+
};
34+

0 commit comments

Comments
 (0)