Skip to content

Commit

Permalink
Add week 13 solutions: insertInterval, mergeIntervals
Browse files Browse the repository at this point in the history
  • Loading branch information
yolophg committed Jul 28, 2024
1 parent be59740 commit 5ede98e
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
30 changes: 30 additions & 0 deletions insert-interval/yolophg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Time Complexity: O(n log n)
// Space Complexity: O(n)

var insert = function (intervals, newInterval) {
// append the newInterval to the intervals array
intervals.push(newInterval);

// sort the intervals array by start time
intervals.sort((a, b) => a[0] - b[0]);

// to store merged intervals
let result = [];

// iterate through the sorted intervals array
for (let i = 0; i < intervals.length; i++) {
// if the result array is empty or the current interval does not overlap with the last interval
if (result.length === 0 || result[result.length - 1][1] < intervals[i][0]) {
result.push(intervals[i]); // Add the current interval to the result array
} else {
// if there is an overlap, merge the current interval with the last interval
result[result.length - 1][1] = Math.max(
result[result.length - 1][1],
intervals[i][1]
);
}
}

// return the final merged intervals
return result;
};
31 changes: 31 additions & 0 deletions merge-intervals/yolophg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time Complexity: O(n log n)
// Space Complexity: O(n)

var merge = function (intervals) {
// sort the intervals by their start time
intervals.sort((a, b) => a[0] - b[0]);

// to manage merged intervals
let stack = [];

// push the first interval onto the stack
stack.push(intervals[0]);

// iterate through the sorted intervals
for (let i = 1; i < intervals.length; i++) {
// get the top interval from the stack
let top = stack[stack.length - 1];

// if the current interval overlaps with the top interval
if (top[1] >= intervals[i][0]) {
// merge the intervals by updating the end of the top interval
top[1] = Math.max(top[1], intervals[i][1]);
} else {
// if there is no overlap, push the current interval onto the stack
stack.push(intervals[i]);
}
}

// return the final merged intervals
return stack;
};

0 comments on commit 5ede98e

Please sign in to comment.