Start learning free

LESSON 549 OF 671 · INTERVALS

Can Attend All Meetings in JavaScript: Sort by Start Time

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

    JAVASCRIPT · INTERVALS

    Can Attend All Meetings in JavaScript, explained

    Problem overview

    The method canAttendMeetings receives intervals, an array where each meeting is a pair [start, end]. It returns true if one person could attend every meeting, and false if any two of them overlap. Two meetings overlap when one starts while the other is still going. Meetings that only touch, like [1,2] and [2,3], don't overlap, because the person can leave one at time 2 and enter the next at time 2. With no meetings, the answer is true.

    For [[0,30],[5,10],[15,20]] the answer is false, since [5,10] starts at 5 while [0,30] is running. For [[7,10],[2,4]] it is true, even though the input isn't in order. For [[1,2],[2,3],[3,4]] it is true: each meeting starts exactly when the previous one ends. The lesson asks for O(n log n) time.

    Approach: sort, then compare neighbors

    Comparing every pair of meetings takes O(n²) time, which is too slow for 100,000 meetings. Sorting by start time makes the problem local: in sorted order, a clash can only happen between two neighbors.

    The reason is that if no clash has appeared so far, each earlier meeting ended before the next one started. So the meeting just before the current one is the one that ends last, and it is the only one worth comparing with. After sorting, one pass is enough: meeting i clashes with the meeting before it exactly when it starts before that meeting ends.

    The sort costs O(n log n) and is the slowest part. The pass after it costs O(n).

    Step by step

    1. Sort intervals by start. Call sort with a compare function (first, second) => first[0] - second[0]. A negative result places first before second, so the earlier start comes first.
    2. Loop i from 1 while i < intervals.length. The first meeting has nothing before it to clash with, so the loop starts at the second.
    3. Test intervals[i][0] < intervals[i - 1][1]: does meeting i start before the previous one ends? Use < and not <=, because a meeting that starts exactly when the previous one ends only touches it.
    4. Return false inside that 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. With zero or one meeting the loop doesn't run, and the answer is true as well.

    The solution in JavaScript

    class Solution {
        canAttendMeetings(intervals) {
            intervals.sort((first, second) => first[0] - second[0]);
            for (let i = 1; i < intervals.length; i++) {
                if (intervals[i][0] < intervals[i - 1][1]) {
                    return false;
                }
            }
            return true;
        }
    }
    

    The compare function is the important JavaScript detail. Array.prototype.sort() with no compare function converts the elements to strings and sorts them as text. For plain numbers, [10, 9, 1].sort() gives [1, 10, 9]. For pairs it is just as wrong, because each pair becomes a string such as "10,12":

    const meetings = [[2, 4], [10, 12], [9, 10]];
    console.log(JSON.stringify(meetings.sort()));
    // [[10,12],[2,4],[9,10]]
    console.log(JSON.stringify(meetings.sort((a, b) => a[0] - b[0])));
    // [[2,4],[9,10],[10,12]]
    

    Subtracting the starts is a safe compare here, because the values are small non-negative integers. Note also that sort works in place: after the call, the caller's intervals array is reordered. The lesson's method does that on purpose, but it is something to remember if the original order matters elsewhere. For [[7,10],[2,4]], the array holds [[2,4],[7,10]] afterwards.

    Complexity

    Sorting takes O(n log n) time and the loop takes O(n), so the total is O(n log n). Beyond the sort's own working memory, the method stores only the loop index.

    Edge cases and common mistakes

    • Empty input or one meeting. [] and [[3,4]] both return true, because the loop has nothing to compare.
    • Touching meetings. [[1,2],[2,3],[3,4]] returns true. Using <= would wrongly reject it.
    • Forgetting to sort. The same neighbor check on the unsorted [[7,10],[2,4]] compares 2 with 10 and returns false, although the meetings never overlap. The check only means something once the meetings are in order of start.
    • Sorting without a compare function. It orders the pairs as text, which can put [10,12] before [2,4].
    • A long meeting hiding smaller ones. In [[1,5],[2,3],[6,7]] the clash is found at [2,3], which starts before 5, so the answer is false.

    Testing

    Results from the reference solution:

    [[0,30],[5,10],[15,20]]  -> false
    [[7,10],[2,4]]           -> true
    [[1,2],[2,3],[3,4]]      -> true
    []                       -> true
    [[3,4]]                  -> true
    [[1,5],[2,3],[6,7]]      -> false
    
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free