15% off all plans & roadmaps Use code
See plansMeeting Rooms
- LeetCode 252
- Easy
- Greedy Patterns
- Interval Merging/Scheduling
Updated
TL;DR: Decide whether one person can attend every meeting, where meetings touching at an endpoint do not conflict. Sort by start time, then compare each meeting's start with the previous meeting's end.
Problem
You are given a list intervals where each element [start, end] is one meeting. Implement Solution.canAttendMeetings to decide whether one person can attend all of the meetings.
Two meetings conflict when their time ranges overlap. A meeting that ends at time t and another that starts at time t do not conflict. Return true if every meeting can be attended, and false otherwise.
Example 1
Input: intervals = [] Output: true Explanation: With no meetings there is nothing to conflict.
Example 2
Input: intervals = [[8,11],[2,5],[5,8]] Output: true Explanation: Each meeting ends exactly when the next one begins, and touching at an endpoint is allowed.
Example 3
Input: intervals = [[1,4],[3,6],[7,9]] Output: false Explanation: The first two meetings overlap from time 3 to time 4, so you cannot attend both.
Constraints
0 <= intervals.length <= 10^4- Each element of
intervalshas exactly 2 integers. 0 <= intervals[i][0] < intervals[i][1] <= 10^6- The intervals can come in any order.
Constraints that matter
- n is at most 10^4, so checking every pair costs about 5 * 10^7 comparisons. That is feasible in compiled languages but wasteful, and it is the cost sorting removes.
- Times go up to 10^6, so an array indexed by time has about a million cells. That makes a time-slot sweep possible, and it is cheap enough to allocate once.
- Every interval has start < end, so no meeting has zero length. You never need to handle empty or reversed intervals.
- The input is unsorted, so comparing neighbours in the given order is wrong. You must impose an order before any adjacent check.
- The list can be empty, and the answer is then true. Loops that start at index 1 must not crash on length 0.
Hints
Hint 1
This is an interval scheduling problem, and the pattern is sorting followed by an adjacent comparison.
Hint 2
Take each pair of meetings and test whether they overlap.
Solution
Intuition
This is an interval scheduling problem, and the pattern is sorting followed by an adjacent comparison. The question is whether any two intervals overlap. Asking that of all pairs is expensive, so you look for an order that makes only some pairs matter.
Picture people queuing at one door in order of arrival time. Each person only checks whether the person right ahead has already left, since the previous meeting's end is that departure.
Sort the meetings by start time. Now take any meeting and ask which earlier meeting could still be running when it starts. If any earlier meeting is still running, then the one right before it in sorted order is also running, or it already caused a conflict. That is why one neighbour check is enough.
Here is the reason in more detail. Suppose meeting A comes before meeting C, and meeting B sits between them in sorted order. If A overlaps C, then A ends after C starts. C starts no earlier than B starts. So A ends after B starts, which means A and B already overlap, and the scan would have caught that pair first.
The touching rule decides the comparison operator. A meeting ending at 5 and another starting at 5 are fine, so a conflict needs the next start to be strictly less than the previous end. Use <, not <=.
You can spot this pattern by looking for words like overlap, conflict or schedule, plus input that arrives in any order. Whenever a problem asks about overlap among many ranges, try sorting by start first.
Worked example
Input: intervals = [[8, 11], [2, 5], [5, 8]] Output: true Explanation: Sorted by start time the meetings are [2,5], [5,8], [8,11]. Each one starts at the exact moment the previous one ends, so no two meetings share any time and one person can attend all three.
Approach 1: Brute force: compare every pair
Take each pair of meetings and test whether they overlap. Two meetings [a, b] and [c, d] overlap when each one starts before the other ends: a < d and c < b. If any pair passes this test, return false.
This needs no ordering and no extra memory. It is also the easiest version to get right, which makes it a useful reference when you test a faster solution.
Steps
- Loop
iover every meeting index. - For each
i, loopjover every index afteri. - Read the two meetings as
[a, b]and[c, d]. - If
a < dandc < b, the meetings overlap, so return false. - If no pair overlaps after both loops finish, return true.
Dry run
Run it on [[8,11],[2,5],[5,8]]. There are 3 pairs.
- Pair (0,1):
[8,11]and[2,5]. Check8 < 5, which is false. No overlap. - Pair (0,2):
[8,11]and[5,8]. Check8 < 8, which is false. No overlap. - Pair (1,2):
[2,5]and[5,8]. Check2 < 8is true, but5 < 5is false. No overlap.
No pair overlaps, so the function returns true.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
Let n be the number of meetings. The two nested loops visit n * (n - 1) / 2 pairs, and each pair costs a constant number of comparisons, so time is O(n^2). With n = 10^4 that is about 5 * 10^7 checks. The code stores only a few loop variables, so extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
n = len(intervals)
for i in range(n):
for j in range(i + 1, n):
a, b = intervals[i]
c, d = intervals[j]
# overlap when each starts before the other ends
if a < d and c < b:
return False
return True
JavaTested in our runner
import java.util.*;
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
int n = intervals.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// overlap when each starts before the other ends
if (intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1]) {
return false;
}
}
}
return true;
}
};
C++Tested in our runner
using namespace std;
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
int n = intervals.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// overlap when each starts before the other ends
if (intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1]) {
return false;
}
}
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
const n = intervals.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// overlap when each starts before the other ends
if (intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1]) {
return false;
}
}
}
return true;
};
GoTested in our runner
func canAttendMeetings(intervals [][]int) bool {
n := len(intervals)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
// overlap when each starts before the other ends
if intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1] {
return false
}
}
}
return true
}
C#Tested in our runner
public class Solution {
public bool canAttendMeetings(int[][] intervals) {
int n = intervals.Length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// overlap when each starts before the other ends
if (intervals[i][0] < intervals[j][1] && intervals[j][0] < intervals[i][1]) {
return false;
}
}
}
return true;
}
}
Approach 2: Time-slot sweep with a difference array
What's slow: the brute force compares pairs that have nothing to do with each other, such as a meeting at time 1 and one at time 900000. The insight that fixes it is to think in time instead of in pairs. A person can attend everything only if no moment of time is covered by two meetings.
Times are integers up to 10^6, so you can keep one counter per time slot. A meeting [s, e] covers slots s through e - 1. Add 1 at index s and subtract 1 at index e, then take a running sum.
The running sum at slot t is the number of meetings active during [t, t+1). If it ever exceeds 1, two meetings share time. The subtraction at e lands on the same index as an addition for a meeting that starts at e. Those cancel before the running sum is read, which is exactly the touching rule.
Steps
- Allocate an integer array
diffof size 1,000,002, filled with zeros. - For each meeting
[s, e], add 1 todiff[s]and subtract 1 fromdiff[e]. - Set a running total to 0.
- Walk through
difffrom index 0 upward, adding each cell to the running total. - If the running total ever exceeds 1, return false.
- If the walk ends with the total never above 1, return true.
Dry run
Use [[8,11],[2,5],[5,8]]. Applying the three meetings changes these cells:
[8,11]:diff[8] += 1,diff[11] -= 1.[2,5]:diff[2] += 1,diff[5] -= 1.[5,8]:diff[5] += 1,diff[8] -= 1.
The net values are diff[2] = 1, diff[5] = 0, diff[8] = 0 and diff[11] = -1, with all other cells 0. The running total is 0 before index 2, becomes 1 at index 2, stays 1 through index 10, and drops to 0 at index 11. It never reaches 2, so the function returns true.
Complexity
| Time | O(n + M) |
|---|---|
| Space | O(M) |
Let n be the number of meetings and M the largest possible time, here 10^6. Filling the array and the final walk each touch M + 2 cells, and the update loop touches n meetings twice, so time is O(n + M). The array holds M + 2 integers regardless of n, so space is O(M). This beats O(n^2) at n = 10^4 but allocates a million cells even for three meetings.
PythonTested in our runner
from typing import List, Optional
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
diff = [0] * (10**6 + 2)
for s, e in intervals:
diff[s] += 1 # a meeting begins
diff[e] -= 1 # a meeting ends; cancels a start at the same time
active = 0
for d in diff:
active += d
if active > 1:
return False
return True
JavaTested in our runner
import java.util.*;
class Solution {
public boolean canAttendMeetings(int[][] intervals) {
int[] diff = new int[1000002];
for (int[] m : intervals) {
diff[m[0]]++; // a meeting begins
diff[m[1]]--; // a meeting ends
}
int active = 0;
for (int d : diff) {
active += d;
if (active > 1) {
return false;
}
}
return true;
}
};
C++Tested in our runner
using namespace std;
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
vector<int> diff(1000002, 0);
for (const auto& m : intervals) {
diff[m[0]]++; // a meeting begins
diff[m[1]]--; // a meeting ends
}
int active = 0;
for (int d : diff) {
active += d;
if (active > 1) {
return false;
}
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
const diff = new Int32Array(1000002);
for (const m of intervals) {
diff[m[0]] += 1; // a meeting begins
diff[m[1]] -= 1; // a meeting ends
}
let active = 0;
for (let t = 0; t < diff.length; t++) {
active += diff[t];
if (active > 1) {
return false;
}
}
return true;
};
GoTested in our runner
func canAttendMeetings(intervals [][]int) bool {
diff := make([]int, 1000002)
for _, m := range intervals {
diff[m[0]]++ // a meeting begins
diff[m[1]]-- // a meeting ends
}
active := 0
for _, d := range diff {
active += d
if active > 1 {
return false
}
}
return true
}
C#Tested in our runner
public class Solution {
public bool canAttendMeetings(int[][] intervals) {
int[] diff = new int[1000002];
foreach (int[] m in intervals) {
diff[m[0]]++; // a meeting begins
diff[m[1]]--; // a meeting ends
}
int active = 0;
foreach (int d in diff) {
active += d;
if (active > 1) {
return false;
}
}
return true;
}
}

Solution pattern
Interval Merging/Scheduling
Part of Greedy Patterns
Approach 3: Sort by start, then scan neighboursOptimalInterval Merging/Scheduling
What's slow: the sweep depends on the size of the time range, not on the number of meetings, and it breaks down if times grow to 10^9. The pairwise check depends on n squared. The insight that fixes both is that sorting by start time makes only adjacent pairs matter.
After sorting, any meeting that overlaps an earlier meeting also overlaps its immediate predecessor. So you compare each meeting's start with the previous meeting's end and stop at the first strict overlap. The cost is dominated by the sort, and it does not depend on how large the time values are.
Steps
- If there are fewer than 2 meetings, the loop below never runs and the answer is true.
- Sort the meetings by start time, ascending.
- Loop
ifrom 1 to n - 1. - Compare
intervals[i][0]withintervals[i - 1][1]. - If the current start is strictly less than the previous end, return false.
- If the loop finishes without a conflict, return true.
Dry run
Input [[8,11],[2,5],[5,8]]. After sorting by start, the list is [[2,5],[5,8],[8,11]]. The table traces the scan.
| i | previous | current | check (current start < previous end) | action |
|---|---|---|---|---|
| 1 | [2,5] | [5,8] | 5 < 5 is false | continue |
| 2 | [5,8] | [8,11] | 8 < 8 is false | continue |
| end | no conflict found | return true |
Both checks are false because each meeting starts exactly when the last one ends. The scan finishes and returns true, matching the expected output.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(1) extra, or O(n) if the sort copies |
Let n be the number of meetings. Sorting costs O(n log n) comparisons, and the scan makes at most n - 1 constant-time checks, so time is O(n log n). The scan keeps only the loop index. Extra space is whatever the sort uses: O(log n) stack for in-place sorts in C++ and Java, and O(n) in languages that copy or use a merge-based sort such as Python and JavaScript.
PythonTested in our runner
from typing import List, Optional
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
meetings = sorted(intervals, key=lambda m: m[0])
for i in range(1, len(meetings)):
# strict less than: touching endpoints are allowed
if meetings[i][0] < meetings[i - 1][1]:
return False
return True
JavaTested in our runner
import java.util.*;
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++) {
// strict less than: touching endpoints are allowed
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
};
C++Tested in our runner
using namespace std;
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end(),
[](const vector<int>& a, const vector<int>& b) { return a[0] < b[0]; });
for (int i = 1; i < (int)intervals.size(); i++) {
// strict less than: touching endpoints are allowed
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
const meetings = intervals.slice().sort((a, b) => a[0] - b[0]);
for (let i = 1; i < meetings.length; i++) {
// strict less than: touching endpoints are allowed
if (meetings[i][0] < meetings[i - 1][1]) {
return false;
}
}
return true;
};
GoTested in our runner
import "sort"
func canAttendMeetings(intervals [][]int) bool {
sort.Slice(intervals, func(i, j int) bool {
return intervals[i][0] < intervals[j][0]
})
for i := 1; i < len(intervals); i++ {
// strict less than: touching endpoints are allowed
if intervals[i][0] < intervals[i-1][1] {
return false
}
}
return true
}
C#Tested in our runner
public class Solution {
public bool canAttendMeetings(int[][] intervals) {
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
for (int i = 1; i < intervals.Length; i++) {
// strict less than: touching endpoints are allowed
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
}
Common mistakes
- Scanning the input without sorting. Neighbours in the given order are not neighbours in time, so
[[1,4],[10,12],[3,6]]slips through. Sort byinterval[0]first. - Using
intervals[i][0] <= intervals[i-1][1]as the conflict test. That flags[2,5]and[5,8]as overlapping, but the problem allows them. Use strict<. - Comparing the current start with the previous start, or the current end with the previous end. The conflict test is current start against previous end. Mixing them up misses real overlaps.
- Starting the loop at index 0 and reading
intervals[i-1]. That reads index -1 in Python (a silent wrong answer) and crashes in other languages. Start ati = 1. - Sorting by end time and then checking
start < previous endwith the same rule. The adjacent-neighbour argument depends on start order, so sort by start. - In the time-slot sweep, using an array of size 10^6 instead of 10^6 + 2, or marking slot
eas busy. An end time of 10^6 writes out of bounds, and treatingeas occupied turns touching meetings into conflicts.
Edge cases
[]returns true, since there are no meetings to conflict.- A single meeting such as
[[0,1]]returns true. The scan loop does not run. - Touching meetings
[[2,5],[5,8]]return true. The boundary is not a conflict. - Identical meetings
[[3,6],[3,6]]return false. After sorting,3 < 6fires. - One long meeting containing a short one,
[[1,10],[3,4]], returns false. The sorted neighbour check catches it:3 < 10. - Unsorted input where the conflict is far apart in the list, such as
[[1,4],[20,30],[3,6]], returns false. Sorting brings[1,4]and[3,6]together. - Maximum values like
[[0,1000000]]return true, and[[0,1000000],[999999,1000000]]returns false. Check that the sweep array is large enough.
Follow-ups interviewers ask
- How would you find the minimum number of rooms needed for all meetings (Meeting Rooms II)?
- Sort the start times and the end times separately. Walk through the starts with a pointer into the ends. If a meeting starts before the earliest unfinished end, you need another room. Otherwise you reuse one by advancing the end pointer. A min-heap of end times gives the same answer. Both run in O(n log n).
- What if meetings arrive one at a time and you must check each new one against the schedule?
- Keep the accepted meetings in a balanced ordered set keyed by start time. For a new meeting, find the nearest meeting that starts before it and the nearest that starts after it. Only those two neighbours can conflict, by the same argument as the sorted scan. Each insert costs O(log n).
- What changes if meetings that touch at an endpoint also count as conflicts?
- Switch the strict comparison to
<=, so the test becomes current start <= previous end. In the time-slot sweep, mark closed intervals by subtracting at indexe + 1instead ofe. Everything else, including the sort and the complexity, stays the same.
Meeting Rooms FAQ
What is the time complexity of Meeting Rooms?
The sort-then-scan solution runs in O(n log n), where n is the number of meetings. The sort dominates, and the scan adds only O(n). The brute force pair check is O(n^2), and the time-slot sweep is O(n + M) with M = 10^6.
Why use sorting for Meeting Rooms (LeetCode 252)?
Sorting by start time means any meeting that overlaps an earlier one also overlaps its immediate predecessor. You then compare only n - 1 neighbouring pairs instead of n * (n - 1) / 2 pairs. Without sorting, adjacent entries in the input have no relation in time.
Why is the overlap check start < previous end and not start <= previous end?
The problem says a meeting ending at time t and another starting at t do not conflict. With <=, the pair [2,5] and [5,8] would be wrongly rejected. Strict < accepts that pair and still rejects real overlaps like [1,4] and [3,6].
Can Meeting Rooms be solved in O(1) extra space?
Yes, if you are allowed to sort the input in place. In-place sorts in Java and C++ use at most O(log n) stack, and the scan uses constant space. Python's sorted and a JavaScript copy both allocate O(n), though you can call intervals.sort to avoid the copy. Skipping the sort entirely means using the O(n^2) pair check.
How is Meeting Rooms different from Meeting Rooms II?
Meeting Rooms asks a yes or no question: do any two meetings overlap. Meeting Rooms II asks for the largest number of meetings running at the same moment, which is the number of rooms needed. Both start by ordering the times, but the second needs a heap or two sorted arrays.
Does the order of ties in the sort matter?
No. If two meetings share a start time, they overlap because every meeting has start < end. Whichever comes first, the second one has start < the first one's end, so the scan returns false.
Asked at
See which companies ask this — Pro
Related problems
- Merge Intervals · same technique: Interval Merging/Scheduling
- Non-overlapping Intervals · same technique: Interval Merging/Scheduling
- Insert Interval · same technique: Interval Merging/Scheduling
- Divide Intervals Into Minimum Number of Groups · same technique: Interval Merging/Scheduling
- Best Time to Buy and Sell Stock · same pattern: Greedy Patterns
- Lemonade Change · same pattern: Greedy Patterns
- Assign Cookies · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns