Start learning free

LESSON 549 OF 671 · INTERVALS

Can Attend All Meetings in Java: 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

    JAVA · INTERVALS

    Can Attend All Meetings in Java, explained

    Problem overview

    The method canAttendMeetings receives an int[][] named intervals, where each int[] holds a meeting's start and end time. It returns true if one person can attend every meeting and false if any two overlap. Meetings that only touch, such as [1,2] and [2,3], don't overlap, and with no meetings at all the answer is true.

    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, even though the meetings are not in order.

    The statement asks for O(n log n) time, where n is the number of meetings.

    Approach: sort by start, then compare neighbors

    Comparing every pair of meetings costs O(n²), which is too slow for up to 100,000 meetings. Sorting by start time fixes that. Once the meetings are in order, a clash can only happen between neighbors. Suppose no clash has appeared 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 one ends, they overlap. If it starts at or after that end, it can't overlap any earlier meeting either.

    So the work splits into a sort, O(n log n), and one pass over the neighbors, O(n). The sort is the slowest part and sets the total.

    Step by step

    1. Sort intervals by start with Arrays.sort and a comparator lambda (first, second) -> first[0] - second[0]. A negative result puts 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.
    3. Compare with the meeting before. Test intervals[i][0] < intervals[i - 1][1]: does meeting i start before meeting i - 1 ends? Use <, not <=. A meeting that starts exactly when the previous one ends only touches it.
    4. Return false inside the if. One clash settles the answer, so the rest don't matter.
    5. Return true after the loop. No meeting started before the one before it ended. With zero or one meeting the loop never runs, and true is correct.

    The solution in Java

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

    Java details worth noticing:

    • Sorting an int[][]. Arrays.sort(array, comparator) works on arrays of objects, and each int[] is an object, so a comparator can order the rows. A single int[] of primitives can't take one. Arrays lives in java.util, so outside the lesson's editor the file needs import java.util.Arrays;.
    • The sort happens in place. It reorders the array the caller passed in. That is fine here, but a caller who needs the original order must pass a copy.
    • Subtraction as a comparator can overflow. The lesson's values stay within 0 to 1,000,000, so first[0] - second[0] is always safe. With huge values it is not: for starts of 2,000,000,000 and -2,000,000,000 the difference wraps to -294967296, the comparator claims the larger value is smaller, and the sorted result stays [[2000000000, 2], [-2000000000, 1]]. Integer.compare(first[0], second[0]) has no such problem.
    • Lambda parameter names. first and second are the two rows being compared. Their types are inferred from the array's element type.

    Complexity

    Time: O(n log n). Sorting dominates, and the loop that follows is a single pass of O(n).

    Space: the loop uses no extra memory. The sort itself needs some working space for the objects it orders, typically up to O(n), so say O(n) in the worst case rather than O(1).

    Edge cases and common mistakes

    • No meetings or one meeting. [] and [[1,5]] both return true.
    • Touching meetings. [[1,2],[2,3],[3,4]] returns true. Writing <= in the comparison would wrongly return false.
    • Unsorted input. [[7,10],[2,4]] returns true only because of the sort. Comparing neighbors without sorting would see a start of 2 before an end of 10 and wrongly say false.
    • A long meeting around short ones. For [[1,10],[2,3],[11,12]] the method returns false when it reaches [2,3], which starts before [1,10] ends.
    • Comparing with intervals[0] each time. After sorting, only the meeting just before matters.

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