Problem overview
CanAttendMeetings receives the meetings as an int[,], one meeting per row: the start in column 0 and the end in column 1. It returns true if one person can attend all of them, and false if two meetings overlap.
Two meetings overlap when one starts while the other is still going. Meetings that only touch don't overlap: [1,2] and [2,3] are fine, because the person leaves one at time 2 and enters the next at time 2. With no meetings the answer is true.
For {{0,30},{5,10},{15,20}} the answer is false, since the meeting at 5 starts inside [0,30]. For {{7,10},{2,4}} it is true, even though the rows are not in time order. For {{1,2},{2,3},{3,4}} it is true: each meeting starts exactly when the previous one ends.
Approach: sort, then compare neighbours
Comparing every pair of meetings costs O(n²), too slow for 100,000 meetings. Sorting by start time makes the check much simpler. In sorted order, if any two meetings overlap, then two neighbouring ones do. So after sorting, one pass comparing each meeting with the one before it is enough.
Why only the one just before? Suppose no clash was found so far. Then each earlier meeting ended before the next one started, so the meeting just before the current one is the one that ends last. If the current meeting starts before that end, it clashes. If it doesn't, it clashes with none of the earlier ones either.
Sorting dominates the cost at O(n log n); the pass afterwards is O(n).
There is a C# wrinkle. An int[,] is one block of memory, not an array of row arrays, so you can't sort its rows directly. The lesson sorts an array of row numbers instead and uses it to visit the rows in order of start.
Step by step
- Store the row count in
rowswithintervals.GetLength(0).GetLength(0)is the size of the first dimension;GetLength(1)would give the columns. - Create
order, anint[]of sizerows. It will hold row numbers. - Fill it with
0, 1, ..., rows - 1in a one-lineforloop. Each number stands for one row ofintervals. - Sort
orderwithArray.Sortand a comparison lambda(first, second)that returnsintervals[first, 0] - intervals[second, 0]. A negative result putsfirstearlier, so rows with an earlier start come first. Afterwardsorder[0]is the row of the meeting that starts first. - Loop
ifrom 1 whilei < rows. The first meeting has nothing before it to clash with. - Test for a clash: is the start of meeting
order[i]less than the end of meetingorder[i - 1]? Use<, not<=, so touching meetings stay legal. - Return
falseinside theif. One clash settles it. - Return
trueafter the loop. With zero or one meeting the loop doesn't run, and the answer istrue.
For the rows {{7,10},{2,4},{1,2}}, the sorted order is 2, 1, 0: the meeting [1,2] first, then [2,4], then [7,10].
The solution in C#
class Solution {
public bool CanAttendMeetings(int[,] intervals) {
int rows = intervals.GetLength(0);
int[] order = new int[rows];
for (int i = 0; i < rows; i++) order[i] = i;
Array.Sort(order, (first, second) => intervals[first, 0] - intervals[second, 0]);
for (int i = 1; i < rows; i++) {
if (intervals[order[i], 0] < intervals[order[i - 1], 1]) {
return false;
}
}
return true;
}
}
Details worth knowing:
- The comparison lambda.
Array.Sort(array, comparison)takes a function that returns a negative number, zero or a positive number. The lambda can readintervalsbecause it captures the method's parameter. - Subtraction as a comparison is safe only for small numbers. With starts up to 1,000,000 the difference fits easily in an
int. With values near the limits ofint, the subtraction wraps around and sorts wrongly: with starts -2000000000 and 2000000000, the sorted order comes out as row 1 before row 0.intervals[first, 0].CompareTo(intervals[second, 0])has no such problem. - Rows are not arrays.
intervals[i]doesn't compile for anint[,]; both indexes go in one pair of brackets,intervals[i, 0]. - The input is not reordered. Only
orderis sorted. The caller'sintervalsstays unchanged.
Complexity
Time: O(n log n) for the sort, plus O(n) for the pass, which gives O(n log n) overall.
Space: O(n) for the order array.
Edge cases and common mistakes
- No meetings. An empty array has zero rows, and the method returns
true. - One meeting.
{{4,9}}returnstrue. - Touching meetings.
{{1,2},{2,3}}is fine. Using<=in the check would wrongly returnfalse. - A meeting inside another.
{{1,5},{2,3}}returnsfalse: the meeting at 2 starts before 5. - Unsorted input.
{{3,6},{1,4}}returnsfalse. Comparing neighbours in the original order, without sorting, would miss clashes between meetings that are not next to each other in the input. - Comparing starts only. Two meetings can have different starts and still overlap, so the check must use the previous end.
Testing
{{0,30},{5,10},{15,20}}givesfalse.{{7,10},{2,4}}givestrue.{{1,2},{2,3},{3,4}}givestrue.- No meetings gives
true. {{1,5},{2,3}}givesfalse.{{3,6},{1,4}}givesfalse.
