My Calendar I

MediumDesign · Ordered Set (TreeMap)🧩 Ordered Set (TreeMap)LeetCode #729 ↗Updated

Problem

Build a class MyCalendar whose book(start, end) tries to reserve the half-open interval [start, end). If it overlaps any event already accepted, reject it and return false; otherwise store it and return true. Touching intervals (one ends exactly when the next starts) are fine.
Inputbook(10,20) book(15,25)Outputtrue, false
Inputbook(20,30)Outputtrue

0 ≤ start < end ≤ 109  ·  at most 1000 calls to book

Try it yourself

Java
class MyCalendar {
    public boolean book(int start, int end) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
[s1,e1) and [s2,e2) overlap iff s1 < e2 && s2 < e1. Accepted events never overlap, so if they are kept sorted by start, a new event only has to be checked against its two neighbours.
PatternOrdered Set (TreeMap)

Instinct Keys keep arriving or leaving and you must ask "what is the nearest key below/above x?" or "current min/max" each time - reach for TreeMap/TreeSet.

Memory hack A HashMap with a sense of direction - floor looks down, ceiling looks up, and both answer in log time while the data keeps changing.

Open the Ordered Set (TreeMap) guide →

Approaches

Brute ForceList of Events, Linear Scan

Time O(n) per bookSpace O(n)

Keep every accepted interval in a list. For a new request, test the overlap condition against all of them; append it only if none conflicts.

Java
class MyCalendar {
    private final List<int[]> events = new ArrayList<>();

    public boolean book(int start, int end) {
        for (int[] e : events) {
            if (e[0] < end && start < e[1]) return false; // overlap
        }
        events.add(new int[]{start, end});
        return true;
    }
}

Trivial and fine for 1000 calls, but each booking scans everything.

At a glance

LevelApproachTimeSpace
Brute ForceList of Events, Linear ScanO(n) per bookO(n)
BetterHand-Rolled BST of IntervalsO(h) per bookO(n)
OptimalTreeMap Floor / Ceiling NeighboursO(log n) per bookO(n)
Common pitfalls
  • Using ≤ in the overlap test — rejects valid touching intervals like [10,20) and [20,30).
  • Checking only the floor neighbour and forgetting the ceiling one (or vice versa).
  • Storing a rejected booking anyway — later checks become wrong.
Interview tips
  • Write the overlap condition first and test it on touching / nested intervals.
  • Ask about call volume: 1000 calls makes O(n) fine, but mention the O(log n) upgrade.
  • Explain why a plain BST can degrade and how TreeMap (red-black tree) avoids it.
Pattern
Ordered set / TreeMap neighbours → insert disjoint intervals and query the closest ones in O(log n).
My notes saved in this browser