252. Meeting Rooms
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Intervals
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven a list of meeting time intervals, determine whether a single person can attend all of them without any two meetings overlapping.
Approach
- Sort intervals by start time; if no two adjacent meetings overlap, the whole schedule is conflict-free.
- After sorting, it suffices to check each consecutive pair: if the next meeting starts before the current one ends, there is a conflict.
- Sorting guarantees that any overlap must appear between adjacent elements, so a single linear scan is sufficient after the sort.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
// Sort by start time so overlaps can only occur between adjacent meetings
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) {
// Overlap exists if the next meeting starts before the current one ends
if (intervals[i][0] < intervals[i - 1][1]) {
return false;
}
}
return true;
}
}; Time O(n log n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
bool canAttendMeetings(vector<vector<int>>& intervals) {
sort(intervals.begin(), intervals.end());
for(int i=1; i<intervals.size(); ++i){
if(intervals[i][0]<intervals[i-1][1]){
return false;
}
}
return true;
}
};
// Time: O(nlogn)
// Space: O(1) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.