Problem overview
The method canAttendMeetings(intervals: number[][]): boolean receives meetings as [start, end] pairs and returns true if one person can attend all of them, and false if any two overlap. Two meetings overlap when one starts before the other ends. Meetings that only touch, like [1,2] and [2,3], don't overlap, and no meetings at all is true.
For [[0,30],[5,10],[15,20]] the answer is false: the meeting [5,10] starts while [0,30] is still going. For [[7,10],[2,4]] the answer is true, even though the meetings are not given in order. The statement asks for O(n log n) time.
Approach: sort by start, then look at neighbors
Comparing every pair of meetings takes O(n²) time, which is too slow for 100,000 meetings. Sorting changes the picture. Once the meetings are ordered by start time, a clash can only show up between two neighbors in the list.
The reason: suppose no clash has been found so far. Then each earlier meeting ended before the next one started, so the meeting just before the current one is also the one that ends last. If the current meeting starts before that end time, it overlaps. If it starts at or after it, it can't overlap any earlier meeting either. So one pass comparing intervals[i][0] with intervals[i - 1][1] is enough.
Sorting costs O(n log n) and the pass costs O(n), so the sort is the slowest part and sets the total.
Step by step
- Sort the meetings by start. Call
sortwith a compare function(first, second) => first[0] - second[0]. A negative result putsfirstbeforesecond, so the earlier start comes first. - Loop from the second meeting.
istarts at 1 and runs whilei < intervals.length. The first meeting has nothing before it to clash with. - Test for a clash. Inside the loop, an
ifchecksintervals[i][0] < intervals[i - 1][1]. Use<, not<=: a meeting that starts exactly when the previous one ends only touches it, and the person can walk from one to the next. - Return
falseon the first clash. One overlap settles the answer, and the later meetings don't matter. - Return
trueafter the loop. No meeting started before the previous one ended. With zero or one meeting the loop doesn't run at all, and the answer istrueas well.
The solution in TypeScript
class Solution {
canAttendMeetings(intervals: number[][]): boolean {
intervals.sort((first, second) => first[0] - second[0]);
for (let i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
}
The TypeScript details worth knowing:
- The compare function is required. Without one,
sort()converts the elements to strings and compares those. Each interval turns into text like"9,10", and text compares character by character, so"100,101"comes before"9,10". Callingsort()with no argument on[[9,10],[100,101]]gives[[100,101],[9,10]], and then the check sees9 < 101and wrongly returnsfalse. With the compare function, the same input givestrue. - Sorting by subtraction.
first[0] - second[0]returns a negative number, zero or a positive number, which is allsortneeds. It is safe here because the times stay small. With values that could be huge or non-numeric, a comparison with<and>is safer. sortchanges the array in place. After the call, the caller'sintervalsis in sorted order. For[[7,10],[2,4]]the array becomes[[2,4],[7,10]]. If the caller needs the original order, sort a copy with[...intervals].sort(...).- Types are erased.
number[][]andbooleanare checked when compiling, but nothing checks at run time that each interval really has two numbers. - Sorting is stable. Meetings with the same start keep their relative order. That doesn't change the answer here, but it is guaranteed in modern JavaScript.
Complexity
Time: O(n log n), where n is the number of meetings. The sort dominates. The loop is O(n).
Space: O(1) extra beyond the sort's own working memory, since the function changes the input array instead of copying it. The memory the sort uses internally depends on the engine, so a copy-based version, which costs O(n), is the price of not changing the caller's array.
Edge cases and common mistakes
- No meetings.
[]returnstrue, since the loop never runs. - One meeting.
[[3,4]]returnstrue. - Touching meetings.
[[1,2],[2,3],[3,4]]returnstrue. Using<=would wrongly givefalse. - A meeting inside another.
[[0,10],[1,2],[3,4]]returnsfalse: after sorting,[1,2]starts before[0,10]ends. - Skipping the sort. Comparing neighbors in the given order gives wrong answers: for
[[5,6],[1,2]]the unsorted check sees1 < 6and returnsfalse, though the meetings don't overlap. - Sorting without a compare function. It sorts as text and can reorder the meetings wrongly, as shown above.
- Comparing the wrong fields. The test is the start of this meeting against the end of the previous one:
[0]ofiand[1]ofi - 1.
Testing
[[0,30],[5,10],[15,20]]givesfalse.[[7,10],[2,4]]givestrue.[[1,2],[2,3],[3,4]]givestrue.[]givestrue.[[0,10],[1,2],[3,4]]givesfalse.[[9,10],[100,101]]givestrue.
