Meeting Rooms

Difficulty: Easy

You're given one person's meeting times, each with a start and end. Return whether they can attend every meeting, meaning no two meetings overlap.

Back-to-back meetings (one ends exactly when the next begins) don't count as a conflict.

Examples

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

The meeting [0,30] overlaps both [5,10] and [15,20], so this person can't attend all of them.

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

[2,4] finishes before [7,10] starts, so there's no conflict.

Input: intervals = [[1,5],[5,8]]
Output: true

These meetings touch at time 5 but don't overlap, so back-to-back is fine.

Constraints

  • 0 <= intervals.length <= 10^4

  • intervals[i].length == 2

  • 0 <= start < end <= 10^6

Approach

The direct approach compares every pair of meetings. If any pair overlaps, the person can't attend everything.

Faster: sort by start time first. If there's any conflict at all, some pair of neighbors in that order will conflict. So one pass comparing each meeting to the one before it catches every conflict.

Solutions

Brute Force — Compare Every Pair

Check every pair of meetings. Intervals [a, b] and [c, d] overlap (not just touch) exactly when a < d and c < b. If any pair overlaps, return false.

function canAttendMeetings(intervals) {
  for (let i = 0; i < intervals.length; i++) {
    for (let j = i + 1; j < intervals.length; j++) {
      const overlaps = intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1];
      if (overlaps) {
        return false;
      }
    }
  }
  return true;
}

Time: O(n^2) — every pair of meetings is checked · Space: O(1) extra space

Optimal — Sort by Start, Check Neighbors

Sort by start time, then check each meeting against the one before it. If a meeting starts before the previous one ends, they conflict. If no neighbors conflict, the whole schedule is fine.

function canAttendMeetings(intervals) {
  const sorted = [...intervals].sort((a, b) => a[0] - b[0]);

  for (let i = 1; i < sorted.length; i++) {
    if (sorted[i][0] < sorted[i - 1][1]) {
      return false;
    }
  }

  return true;
}

Time: O(n log n) — dominated by the sort · Space: O(n) for the sorted copy