Example 1
ready- Input
intervals = [ [ 0, 30 ], [ 5, 10 ], [ 15, 20 ] ]- Expected
false- Why
- the 5–10 meeting starts while 0–30 is still running
Calendars get awkward the moment one minute is promised to two meetings.
You're given intervals, where each [start, end] pair describes one meeting. Return
true when one person can attend every meeting, or false when any two meetings
overlap.
A few ground rules:
start up to, but not including, end.[0, 5] and [5, 10] don't overlap.start == end occupies no time, so it can't clash with another meeting.true.0 <= intervals.length <= 100_000[start, end].0 <= start <= end <= 1_000_000_000Hints
Pick two meetings and ask whether the later start happens before the earlier end. Checking every pair is a correct baseline. How many checks does 100,000 meetings create?
Sort meetings by start time. Once they're chronological, a conflict has nowhere to hide far away from the meeting that came just before it.
After sorting, compare each non-empty meeting's start with the previous non-empty
meeting's end. Use <, not <=, because touching endpoints are allowed.
If the answer is false, could you return one conflicting pair of meetings as well?
Visible cases
intervals = [
[
0,
30
],
[
5,
10
],
[
15,
20
]
]falseintervals = [
[
7,
10
],
[
2,
4
]
]trueintervals = []trueInterview signal
Two meetings overlap when the later start is strictly earlier than the earlier end. Compare every pair and stop as soon as you find that condition. Zero-duration meetings need an explicit skip because they occupy no time.
def can_attend_meetings(intervals: list[list[int]]) -> bool:
for i in range(len(intervals) - 1):
first_start, first_end = intervals[i]
if first_start == first_end:
continue
for j in range(i + 1, len(intervals)):
second_start, second_end = intervals[j]
if second_start == second_end:
continue
later_start = max(first_start, second_start)
earlier_end = min(first_end, second_end)
if later_start < earlier_end:
return False
return TrueTime O(n²) — every pair may need a comparison. Space O(1).
Sort the non-empty meetings by start time. Now a meeting only needs to pass one test: does it begin before the preceding meeting ends? If so, those two overlap. If every adjacent pair passes, no earlier meeting can still be running without having already overlapped the meeting after it.
def can_attend_meetings(intervals: list[list[int]]) -> bool:
meetings = sorted(
(start, end) for start, end in intervals if start < end
)
for i in range(1, len(meetings)):
if meetings[i][0] < meetings[i - 1][1]:
return False
return TrueThe strict < carries the endpoint rule: a start equal to the previous end is safe.
Filtering zero-duration meetings keeps an instant inside a longer meeting from looking
like a real conflict.
Time O(n log n) for sorting, followed by one linear scan. Space O(n) for the sorted copy.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
false