Sweaty Imposter

Meeting Rooms

EasyMerge IntervalsBlind 75JuniorOpen on LeetCodeUpdated

You're given an array of meeting times where intervals[i] = [start_i, end_i] is a meeting that starts at start_i and ends at end_i. Return true if one person could attend every meeting, meaning no two meetings overlap, and false otherwise. A meeting that ends exactly when another begins, like [5,10] and [10,15], is not a conflict. The meetings are listed in no particular order, and an empty list returns true.

Examples

intervals = [[0,30],[5,10],[15,20]] returns false

[0,30][5,10][15,20]051015202530
[0,30] and [5,10] overlap, which already rules it out.

[0,30] is still running when [5,10] starts, and again when [15,20] starts, so no one can attend all three.

intervals = [[7,10],[2,4]] returns true

In time order the meetings are [2,4] then [7,10]. The first ends at 4, before the second starts at 7.

intervals = [[1,5],[5,8]] returns true

The first meeting ends at 5, the same moment the second begins. Back-to-back meetings are fine.

Constraints

  • 0 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= start_i < end_i <= 10^6

Hints

Hint 1

If the meetings were listed in time order, where would a clash have to show up?

Hint 2
A pointer toward the approach
Hint 3
The full approach, step by step

Drill This: Your Approach First

Approach

Sort the meetings by start time. After sorting, any conflict must show up between neighbors: if a meeting overlaps some later one, it also overlaps the meeting right after it, since that one starts even earlier. So scan once and return false as soon as a meeting starts before the previous one ends. The sort dominates; the scan uses O(1) extra space.

Time

O(n log n)

Space

O(n)

Pitfall

Testing start <= previous end flags back-to-back meetings like [5,10] and [10,15] as conflicts. The overlap test is start < previous end. Also make sure an empty list returns true without indexing into it.

Solutions

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