function mergeIntervals(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
const merged = [];
for (const interval of intervals) {
if (!merged.length || merged[merged.length - 1][1] < interval[0]) {
merged.push(interval);
} else {
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], interval[1]);
}
}
return merged;
}
const input = [[1,3],[2,6],[8,10],[15,18]];
console.log(mergeIntervals(input));The code sorts intervals by start time, then merges overlapping ones by extending the end time of the last merged interval.
Intervals [1,3] and [2,6] overlap, so they merge into [1,6]. Others remain separate.
Intervals represent ranges like time slots or numeric ranges that can overlap. Handling them efficiently is key in many real-world problems like calendars, resource allocation, and more.
function isOverlap(a, b) {
return a[1] > b[0] && a[0] < b[1];
}
console.log(isOverlap([1,5], [5,8]));The function returns false because intervals [1,5] and [5,8] only touch at 5 but do not overlap.
The condition uses strict greater and less than, so touching endpoints are not considered overlapping.
function insertInterval(intervals, newInterval) {
const result = [];
let i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[0]) {
result.push(intervals[i]);
i++;
}
while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
result.push(newInterval);
while (i < intervals.length) {
result.push(intervals[i]);
i++;
}
return result;
}
const intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]];
const newInterval = [4,8];
console.log(insertInterval(intervals, newInterval));The new interval [4,8] overlaps with [3,5],[6,7],[8,10]. They merge into [3,10].
Intervals before and after remain unchanged.
The sweep line algorithm sorts all interval start and end points and moves a line across them, updating counts or overlaps efficiently without checking all pairs.
