Command Palette

Search for a command to run...

Problem 15.3 · IntervalsEasy

Meeting Rooms

What it teaches: Sort by start and check neighbours: any overlap means one person can't attend everything.

Practise it on judges as “Meeting Rooms”.

The problem

Given meeting times [start, end], can one person attend all of them? A meeting ending at time t doesn't clash with one starting at t.

Example 1

Input: [[0,30],[5,10],[15,20]]
Output: false

Example 2

Input: [[7,10],[2,4]]
Output: true

Constraints

  • 0 ≤ n ≤ 10⁴

Pattern clues in the wording

  • → Any overlap at all?

These clues point to Merge Intervals: Sort intervals by start; each one either overlaps the last merged interval (extend it) or starts a new one.

Stuck? Take one hint at a time

Solution.java · starter
import java.util.*;

class Solution {
    public boolean canAttendMeetings(int[][] intervals) {
        return true;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
intervals = [[0,30],[5,10],[15,20]]
false
2
intervals = [[7,10],[2,4]]
true

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: sort and compare neighbours

Time O(n log n) Space O(1) extra

Sort by start; if any meeting starts before the previous one ends, return false.

Approach 1
import java.util.Arrays;

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;
    }
}

Verdict: Straightforward.

Before you submit

Edge cases and common mistakes

Test these inputs

  • No meetings
  • Back-to-back meetings (allowed)

Mistakes people make

  • Using ≤, which rejects back-to-back meetings.

Interview

Follow-up questions

How many rooms would be needed instead?