Start learning free

LESSON 267 OF 314 · INTERVALS

Can Attend All Meetings in C#: Sort by Start, O(n log n)

Practice O(n log n) Read the full explanation

Given an array of meeting time intervals where intervals[i] = [starti, endi], determine whether one person could attend all the meetings. Return true if no two meetings overlap, and false otherwise.

Two meetings overlap when one of them starts while the other one is still going: it starts before the other one ends, and ends after the other one starts. Meetings that only touch, like [1,2] and [2,3], don't overlap: the person leaves the first one at 2 and walks into the second one at 2. With no meetings at all, nothing can clash, so the answer is true.

 

Example 1:

Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Explanation: [5,10] starts at 5, while [0,30] is still going, so the person can't be at both.

Example 2:

Input: intervals = [[7,10],[2,4]]
Output: true
Explanation: The meetings aren't sorted, but [2,4] ends before [7,10] starts.

Example 3:

Input: intervals = [[1,2],[2,3],[3,4]]
Output: true
Explanation: Each meeting starts exactly when the one before it ends. They touch, but they don't overlap.

 

Constraints:

  • 0 <= intervals.length <= 105
  • 0 <= starti < endi <= 106

Note:

Your algorithm should run in O(n log n) time, where n is the number of meetings.

STEP 1 OF 8
    Ctrl + Enter to check

    C# · INTERVALS

    Can Attend All Meetings in C#, explained

    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

    1. Store the row count in rows with intervals.GetLength(0). GetLength(0) is the size of the first dimension; GetLength(1) would give the columns.
    2. Create order, an int[] of size rows. It will hold row numbers.
    3. Fill it with 0, 1, ..., rows - 1 in a one-line for loop. Each number stands for one row of intervals.
    4. Sort order with Array.Sort and a comparison lambda (first, second) that returns intervals[first, 0] - intervals[second, 0]. A negative result puts first earlier, so rows with an earlier start come first. Afterwards order[0] is the row of the meeting that starts first.
    5. Loop i from 1 while i < rows. The first meeting has nothing before it to clash with.
    6. Test for a clash: is the start of meeting order[i] less than the end of meeting order[i - 1]? Use <, not <=, so touching meetings stay legal.
    7. Return false inside the if. One clash settles it.
    8. Return true after the loop. With zero or one meeting the loop doesn't run, and the answer is true.

    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 read intervals because 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 of int, 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 an int[,]; both indexes go in one pair of brackets, intervals[i, 0].
    • The input is not reordered. Only order is sorted. The caller's intervals stays 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}} returns true.
    • Touching meetings. {{1,2},{2,3}} is fine. Using <= in the check would wrongly return false.
    • A meeting inside another. {{1,5},{2,3}} returns false: the meeting at 2 starts before 5.
    • Unsorted input. {{3,6},{1,4}} returns false. 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}} gives false.
    • {{7,10},{2,4}} gives true.
    • {{1,2},{2,3},{3,4}} gives true.
    • No meetings gives true.
    • {{1,5},{2,3}} gives false.
    • {{3,6},{1,4}} gives false.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free