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
- Sort the meetings. Declare
sortedwithletasintervals.sortedwith the closure{ $0[0] < $1[0] }. The closure says whether its first argument goes before its second, here by start time.sortedreturns a new array, because the parameterintervalsis a constant. - 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)fori. Write the closing brace right away. - Check for an overlap. Write an
ifthat is true whensorted[i][0] < sorted[i - 1][1]: meetingistarts before the previous one ends. Use<and not<=, because touching meetings are allowed. - Return
falseinside theif. One clash settles the answer, so the rest doesn't matter. - Return
trueafter 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:
sortedversussort.sorted(by:)returns a new array and leaves the original alone.sort(by:)sorts avararray in place. Hereintervalsis a function parameter, which is a constant, sosortedis the one to use.- Trailing closure and
$0,$1. The braces aftersortedare a closure passed as theby:argument.$0and$1are its first and second arguments, each one a meeting of type[Int]. The closure returnstruewhen$0should come first. - Two subscripts.
sorted[i][0]is the start of meetingiandsorted[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 beforesorted.count, so every index is valid. - Why
strideand not1..<sorted.count.stride(from: 1, to: 0, by: 1)is simply empty, so the loop runs zero times when there are no meetings. The range1..<0ends below its start, and building it stops the program with a run-time error. - The empty array. With no meetings,
sortedis empty, the loop is skipped and the method returnstrue. With one meeting the loop is skipped too. - Bool return. Both
return falseandreturn truematch the declaredBooltype.
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.
[]returnstrue. - One meeting.
[[1,5]]returnstrue. - Touching meetings.
[[1,2],[2,3],[3,4]]returnstrue. With<=in the check it would wrongly returnfalse. - Same start time.
[[1,2],[1,3]]returnsfalse: both start at 1, so they overlap, whatever the sort does with ties. - Unsorted input.
[[7,10],[2,4]]returnstrue. 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 isfalse. 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]]givesfalse.[[7,10],[2,4]]givestrue.[[1,2],[2,3],[3,4]]givestrue.[]givestrue.[[1,3],[2,4]]givesfalse.[[1,2],[1,3]]givesfalse.
