Start learning free

LESSON 267 OF 314 · INTERVALS

Can Attend Meetings in Swift: O(n log n) with Sorting

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

    SWIFT · INTERVALS

    Can Attend All Meetings in Swift, explained

    Problem overview

    The method canAttendMeetings receives intervals, an array in which each meeting is an [Int] holding its start and end time. It returns true when one person can attend every meeting, and false when two meetings overlap. A meeting that starts exactly when another ends doesn't overlap it: the person leaves one and walks into the next. With no meetings at all, the answer is true. There can be up to 100,000 meetings, with start < end for each, and the method must run in O(n log n) time.

    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]] it is true: the meetings are out of order, but [2,4] ends before [7,10] starts. For [[1,2],[2,3],[3,4]] it is true, since each one only touches the next.

    Approach: sort by start, then compare neighbours

    Comparing every pair of meetings would take O(n²) time, far too slow for 100,000 meetings. Sorting helps. Once the meetings are ordered by start time, a clash can only show up between two neighbours.

    The reason: suppose no clash has appeared so far. Then every 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 one ends, they overlap. If it starts at or after that time, it starts after all the earlier meetings have ended too.

    So the plan is to sort by start time, then check each meeting against the one before it with a single pass. The sort costs O(n log n), the pass costs O(n), and the sort dominates.

    For the first example, sorting by start gives [[0, 30], [5, 10], [15, 20]], which was already in order. The check at index 1 compares the start 5 with the previous end 30, and 5 < 30, so the answer is false. For the second example, sorting gives [[2, 4], [7, 10]], and 7 is not less than 4, so the loop finishes and the answer is true.

    Step by step

    1. Sort the meetings. Declare sorted with let as intervals.sorted with the closure { $0[0] < $1[0] }. The closure says whether its first argument goes before its second, here by start time. sorted returns a new array, because the parameter intervals is a constant.
    2. Loop over the meetings from the second one on. The first meeting has nothing before it to clash with. Use stride(from: 1, to: sorted.count, by: 1) for i. Write the closing brace right away.
    3. Check for an overlap. Write an if that is true when sorted[i][0] < sorted[i - 1][1]: meeting i starts before the previous one ends. Use < and not <=, because touching meetings are allowed.
    4. Return false inside the if. One clash settles the answer, so the rest doesn't matter.
    5. Return true after the loop. No meeting started before its predecessor ended.

    The solution in Swift

    class Solution {
        func canAttendMeetings(_ intervals: [[Int]]) -> Bool {
            let sorted = intervals.sorted { $0[0] < $1[0] }
            for i in stride(from: 1, to: sorted.count, by: 1) {
                if sorted[i][0] < sorted[i - 1][1] {
                    return false
                }
            }
            return true
        }
    }
    

    The Swift details worth a closer look:

    • sorted versus sort. sorted(by:) returns a new array and leaves the original alone. sort(by:) sorts a var array in place. Here intervals is a function parameter, which is a constant, so sorted is the one to use.
    • Trailing closure and $0, $1. The braces after sorted are a closure passed as the by: argument. $0 and $1 are its first and second arguments, each one a meeting of type [Int]. The closure returns true when $0 should come first.
    • Two subscripts. sorted[i][0] is the start of meeting i and sorted[i - 1][1] is the end of the previous one. Reading outside an array stops the program, but the loop starts at 1 and ends before sorted.count, so every index is valid.
    • Why stride and not 1..<sorted.count. stride(from: 1, to: 0, by: 1) is simply empty, so the loop runs zero times when there are no meetings. The range 1..<0 ends below its start, and building it stops the program with a run-time error.
    • The empty array. With no meetings, sorted is empty, the loop is skipped and the method returns true. With one meeting the loop is skipped too.
    • Bool return. Both return false and return true match the declared Bool type.

    Complexity

    Time: O(n log n). Sorting n meetings takes O(n log n). The loop makes one pass with constant work per meeting.

    Space: O(n). sorted is a new array that holds all the meetings. Sorting a copy in place would not change the time but would also need O(n) for the copy.

    Edge cases and common mistakes

    • No meetings. [] returns true.
    • One meeting. [[1,5]] returns true.
    • Touching meetings. [[1,2],[2,3],[3,4]] returns true. With <= in the check it would wrongly return false.
    • Same start time. [[1,2],[1,3]] returns false: both start at 1, so they overlap, whatever the sort does with ties.
    • Unsorted input. [[7,10],[2,4]] returns true. Without sorting, comparing 2 with 10 would report a clash that isn't there.
    • A long meeting hiding a clash. In [[0,10],[2,3],[11,12]], [0,10] and [2,3] overlap, and the answer is false. The check finds it at index 1.
    • Comparing the wrong fields. The clash test compares a start ([0]) with the previous end ([1]), not two starts or two ends.

    Testing

    Results from running the reference solution:

    • [[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,3],[2,4]] gives false.
    • [[1,2],[1,3]] gives false.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free