Python coding

Attend every meeting

Each meeting is a pair [start, end] with start < end. Return True if one person can attend every meeting, that is, if no two of them overlap. A meeting that ends at time t does not clash with one that starts at t.

The list is not sorted and may be empty. Aim for O(n log n), not a check of every pair.

Besides the tests, one large input (4,000 meetings) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • can_attend_all([[0,30],[5,10],[15,20]]) → false
  • can_attend_all([[7,10],[2,4]]) → true
  • can_attend_all([[1,5],[5,8]]) → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Checking every pair works but is O(n²). Sort the meetings by start first: what does that guarantee about where a clash can appear?

Hint 2

After sorting, if any two meetings clash, some meeting clashes with the very next one. Compare each start with the previous end, using < so back-to-back meetings pass.

Solution and why it works
pythonO(n log n) · O(n)
def can_attend_all(meetings: list[list[int]]) -> bool:
    meetings = sorted(meetings)
    for prev, cur in zip(meetings, meetings[1:]):
        if cur[0] < prev[1]:                 # starts before the previous one ends
            return False
    return True

Sorted by start, a clash always shows up between neighbors: if meeting i overlaps a later j, the meeting right after i starts no later than j, so before i ends. One pass comparing each start with the previous end is enough, and the sort dominates: O(n log n). Two traps: checking neighbors without sorting misses [1,3], [5,7], [2,4], and <= instead of < rejects back-to-back meetings.