AlgoViz

Meeting Rooms

Medium

Sort by start, check each neighbour

Problem

Given meeting time intervals, determine if a person could attend all meetings (no two intervals overlap).

In simple words

Sort by start; if any meeting begins before the previous ends, you can't attend them all.

The idea

Sort the meetings by start time and compare each one only with the meeting immediately before it. After sorting, if a meeting overlaps anything at all it must overlap its predecessor, so one linear pass is enough to answer the question.

The trick

  • Sorted order means only adjacent pairs can conflict.
  • Overlap is `start[i] < end[i-1]`; touching endpoints usually count as fine.
  • O(n log n) for the sort, then O(n) for the scan.

Step 1 of 9. Four intervals on a 0–9 timeline: [1,3], [2,4], [6,8], [7,9]. Sort by start, then sweep.

1/9
Optimal
timeO(n log n)spaceO(n)

Grow the running interval.

1intervals.sort((a,b)=>a[0]-b[0]);2const out = [intervals[0]];3for (const [s, e] of intervals.slice(1)) {4  const last = out.at(-1);5  if (s <= last[1]) last[1] = Math.max(last[1], e);6  else out.push([s, e]);7}

Input

grid
4 × 10

Memory

cells marked
12
groups

Output

merged end
result

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
intervals = [[0,30],[5,10],[15,20]]
Output:
false
Explanation:
[0,30] clashes with the others → can't attend all.

Example 2

Input:
intervals = [[7,10],[2,4]]
Output:
true
Explanation:
They don't overlap → yes.

Example 3

Input:
intervals = [[1,2]]
Output:
true
Explanation:
A single meeting is fine.

Finished the walkthrough? Add it to your streak.