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 a vector 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 5
    Ctrl + Enter to check

    C++ · INTERVALS

    Can Attend All Meetings in C++, explained

    Problem overview

    The method canAttendMeetings receives a vector intervals in which each meeting is a vector<int> holding its start and end time. It returns true when one person can attend every meeting, meaning no two meetings overlap, and false otherwise.

    Meetings that only touch don't overlap: [1,2] and [2,3] can both be attended, because the first ends at 2 as the second begins. With no meetings, the answer is true.

    In [[0,30],[5,10],[15,20]] the meeting [5,10] starts while [0,30] is still going, so the answer is false. In [[7,10],[2,4]] the meetings are out of order, but [2,4] ends before [7,10] starts, so the answer is true. The expected time is O(n log n).

    Approach: sort, then compare neighbours

    Comparing every pair of meetings would take O(n²) time, which is too slow for 100,000 meetings. Sorting by start time removes most of that work. Once the meetings are in order of start, a clash can only appear between neighbours. If no clash has shown up so far, every earlier meeting ended before the next one started, so the meeting just before the current one is the one that ends last. It is enough to check that the current meeting starts at or after the previous meeting's end.

    The sort costs O(n log n), and the check afterwards is a single pass, so the sort sets the total.

    The pairwise idea is easy to write but slow: with 100,000 meetings there are nearly five billion pairs. Sorting first turns the question into one comparison per meeting.

    The function answers only yes or no. It doesn't say which meetings clash, and it returns as soon as it finds the first clash in sorted order, so it may stop long before the end of a large input.

    Step by step

    1. Sort intervals by start. Call sort on intervals.begin() and intervals.end() with a lambda taking two meetings, first and second. It answers "does first go before second?" with first[0] < second[0].
    2. Loop from the second meeting. The index i starts at 1 and runs while i < intervals.size(). The first meeting has nothing before it to clash with.
    3. Test for a clash. Meeting i overlaps the one before it when intervals[i][0] < intervals[i - 1][1]. The comparison is strict: a meeting that starts exactly when the previous one ends only touches it.
    4. Return false inside the if. One clash is enough to answer, so the rest of the meetings don't matter.
    5. Return true after the loop. No meeting started before its predecessor ended. With zero or one meeting the loop doesn't run, and the answer is true as well.

    The solution in C++

    class Solution {
    public:
        bool canAttendMeetings(vector<vector<int>>& intervals) {
            sort(intervals.begin(), intervals.end(), [](auto &first, auto &second) {
                return first[0] < second[0];
            });
            for (int i = 1; i < intervals.size(); i++) {
                if (intervals[i][0] < intervals[i - 1][1]) {
                    return false;
                }
            }
            return true;
        }
    };
    

    The C++ details:

    • The lambda [](auto &first, auto &second) { ... } is a function without a name. The auto parameters (a generic lambda) let the compiler deduce that each one is a vector<int>. Taking them by reference avoids copying the inner vectors on every comparison.
    • The comparison must be a strict "less than". sort requires that equal elements are never ordered before each other. A lambda that returned first[0] <= second[0] breaks that rule and is undefined behaviour.
    • The input is sorted in place. The vector is passed by non-const reference, so the caller's vector is reordered. For [[7,10],[2,4]] it ends up as [[2,4],[7,10]].
    • intervals.size() is unsigned. Comparing it with the signed i works here. The loop starts at 1, so an empty vector simply skips it. Writing the bound as intervals.size() - 1 would wrap around to a huge number for an empty vector.
    • Meetings with equal starts can come out of the sort in either order. That doesn't matter: both then start at the same time, so the second one is at that point before the first one ends and the check finds the clash, since every meeting lasts at least until start + 1.

    Complexity

    Time: O(n log n). Sorting takes O(n log n) comparisons, and the loop is O(n).

    Space: O(1) extra, apart from what the sort itself uses internally. The vector is reordered in place and no copy is made.

    Edge cases and common mistakes

    • No meetings. [] returns true: the loop never runs.
    • One meeting. [[1,5]] returns true for the same reason.
    • Touching meetings. [[1,2],[2,3],[3,4]] returns true. With <= in the check, this input would wrongly return false.
    • A long meeting that contains the others. [[1,10],[2,3],[12,15]] returns false: after sorting, [2,3] starts at 2, before 10.
    • Skipping the sort. Unsorted input like [[7,10],[2,4]] would then compare [2,4] with [7,10] in the wrong direction: 2 < 10 reports a clash that isn't there.
    • Checking only starts against starts. Two meetings can have different starts and still overlap, as [1,3] and [2,6] do. The check has to compare a start with 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.
    • [] gives true.
    • [[1,5],[2,3]] gives false.
    • [[1,3],[2,6]] 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