Intervals represent time ranges or numeric ranges. Why are they commonly used in scheduling problems?
Think about what scheduling means and what you need to check between events.
Intervals represent ranges with start and end points. In scheduling, these ranges show when events happen. Checking if intervals overlap helps find conflicts.
What is the output of the following TypeScript code that merges overlapping intervals?
function mergeIntervals(intervals: number[][]): number[][] {
intervals.sort((a, b) => a[0] - b[0]);
const merged: number[][] = [];
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));Look at how intervals are merged when they overlap.
The code sorts intervals by start time. It merges intervals if they overlap by updating the end time. So [1,3] and [2,6] merge into [1,6].
What error does the following TypeScript code produce when checking if two intervals overlap?
function isOverlap(a: number[], b: number[]): boolean {
return a[1] > b[0] && b[1] > a[0];
}
console.log(isOverlap([1,5], [5,10]));Think about whether intervals that just touch at one point count as overlapping.
The code returns false if intervals only share a boundary point, which is usually correct since touching intervals are not considered overlapping. The condition uses > to exclude touching intervals.
Which option contains a syntax error in this TypeScript code that sorts intervals?
const intervals = [[5,10],[1,3],[2,6]]; intervals.sort((a, b) => a[0] - b[0]); console.log(intervals);
Check for missing parentheses or braces.
Option C is missing the closing parenthesis for the sort method call, causing a syntax error.
Given a list of intervals representing meeting times, what is the maximum number of meetings that overlap at any time?
Consider the intervals: [[1,4],[2,5],[7,9],[3,6]]
Think about counting how many intervals overlap at each point in time.
The intervals [1,4], [2,5], and [3,6] overlap between times 3 and 4, so maximum overlap is 3.
