mediumIntervalsDesignIntervals

My Calendar I

mediumTime: O(n)Space: O(n)

Recognize the pattern

book non-overlapping eventscheck if new event conflictssorted intervals

Brute force idea

The naive version of My Calendar I sounds like this: For each booking, check all existing bookings for overlap — total. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The real unlock in My Calendar I comes when you notice this: Maintain a sorted list of intervals. For each new booking, binary search for the insertion point and check neighbors for overlap. over all operations. Or use a balanced BST (TreeMap). Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for My Calendar I is this: Two intervals [s1,e1) and [s2,e2) overlap if and only if s1 < e2 AND s2 < e1. Checking only the neighboring intervals in sorted order is sufficient. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

One easy way to drift off course in My Calendar I is this: Checking all existing intervals — with a sorted structure, you only need to check the neighbors at the insertion point. The fix is usually to return to the meaning of each move, not just the steps themselves.

Intervals Pattern