My Calendar II solution explained
My Calendar II asks you to build a calendar that accepts a booking [start, end) unless it would make some moment booked three times. Keep two lists: every accepted booking, and the stretches that are already double-booked. A new booking is rejected if it overlaps any double-booked stretch; otherwise its overlaps with existing bookings become new double-booked stretches and it is accepted. That is O(n) per call and O(n²) over n calls, which is the expected answer; a sweep over a sorted map of +1 and -1 changes is the common alternative.
By Evin JohnPublished 8 min read
The problem, restated
Design a class with one method, book(start, end). Each booking covers the times from start up to but not including end. A moment may be covered by two bookings, but never by three. If the new booking would create a moment covered three times, return false and leave the calendar unchanged. Otherwise store it and return true.
| Call | Result | Why |
|---|---|---|
| book(10, 20) | true | The calendar is empty |
| book(15, 25) | true | [15, 20) is now double-booked |
| book(18, 22) | false | [18, 20) would be covered three times |
| book(20, 30) | true | Touches [15, 20) at 20 but half-open intervals do not share that point; [20, 25) becomes double-booked |
| book(22, 24) | false | Falls inside the double-booked [20, 25) |
| book(5, 10) | true | Ends where the first booking starts |
| book(5, 15) | true | Overlaps [5, 10) and [10, 15) once each, never three deep |
The last row is worth a second look. The new booking overlaps two existing ones, but they do not overlap each other inside [5, 15), so no single moment reaches three. Counting how many bookings the new one touches would wrongly reject it.
What the interviewer is checking
This is a design question with a small API, so interviewers look at state: what you store, why it is enough, and how you keep a rejected call from changing anything. They expect you to state the half-open overlap test exactly and to explain why tracking double-booked stretches answers the triple question. Many then ask for a faster or more general version, which is where the sweep and the segment tree come in.
Common follow-ups
- No double bookings at all. That is the simpler version: reject any overlap with an accepted booking.
- Return the largest number of overlapping bookings after each call. The sweep already computes this; return the max running count instead of rejecting.
- Allow at most k overlaps. The sweep generalizes directly; the two-list method does not.
- Huge coordinates and many calls. A segment tree with lazy updates over the time range, built on demand, gives O(log C) per call.
Baseline: count every time unit
If times are small integers, keep an array with one counter per unit of time. A booking [start, end) is allowed when every counter from start to end - 1 is below 2; if so, add 1 to each of them. It is O(end - start) per call and needs memory for the whole time range, so it breaks down for timestamps, but it is simple enough to be obviously right. This page's random tests used it as the reference.
Approach 1: bookings plus double-booked stretches
A moment is triple-booked after adding the new interval exactly when it was already double-booked and the new interval covers it. So if you keep the set of double-booked stretches, the check is a scan for any overlap. If the check passes, the new interval adds a double-booked stretch wherever it overlaps an existing booking, and those overlaps are found with the max-of-starts, min-of-ends rule.
class MyCalendarTwo:
def __init__(self):
self.booked = []
self.double = []
def book(self, start, end):
for s, e in self.double:
if start < e and s < end:
return False
for s, e in self.booked:
lo, hi = max(start, s), min(end, e)
if lo < hi:
self.double.append((lo, hi))
self.booked.append((start, end))
return Trueclass MyCalendarTwo {
constructor() {
this.booked = [];
this.double = [];
}
book(start, end) {
for (const [s, e] of this.double) {
if (start < e && s < end) return false;
}
for (const [s, e] of this.booked) {
const lo = Math.max(start, s);
const hi = Math.min(end, e);
if (lo < hi) this.double.push([lo, hi]);
}
this.booked.push([start, end]);
return true;
}
}Two details make this correct. The rejection check runs before anything is added, so a false result leaves both lists untouched. And the double-booked stretches may overlap each other; that is fine, because the check only asks whether the new interval meets any of them.
Approach 2: a sweep over +1 and -1 changes
Store a map from time to the change in the number of active bookings: +1 at each start, -1 at each end. To test a new booking, add its two changes, then walk the times in sorted order with a running total. If the total ever reaches 3, undo the two changes and return false. Because an end and a start at the same time share one key, the -1 and +1 cancel there, which is exactly the half-open behavior.
class MyCalendarTwoSweep:
def __init__(self):
self.delta = {}
def book(self, start, end):
self.delta[start] = self.delta.get(start, 0) + 1
self.delta[end] = self.delta.get(end, 0) - 1
active = 0
for t in sorted(self.delta):
if t >= end:
break
active += self.delta[t]
if active >= 3:
self.delta[start] -= 1
self.delta[end] += 1
return False
return TrueThe loop stops at end because no later time can be affected by the new booking. One cost to mention: a rejected call can leave keys whose change is back to zero, so the map grows with every call, not only accepted ones; deleting zero entries on rollback fixes that if it matters. In Java or C++, a TreeMap or std::map keeps the keys sorted so each call is O(n) instead of paying for a sort; in Python, a sorted container library does the same job, but a plain dict and sorted() is fine to write in an interview as long as you state the cost.
Approach 3, described: a segment tree
If the interviewer pushes for many calls over a huge time range, describe a segment tree over time that stores, for each node, the maximum number of bookings covering any moment in its range, with lazy additions for whole ranges. A booking first queries the max over [start, end); if it is 2 or more, reject; otherwise add 1 over the range. Nodes are created only when touched, so memory grows with the number of calls rather than the range. Most interviews accept this as a spoken extension rather than code.
Complexity
| Approach | Per call | Memory |
|---|---|---|
| Counter per time unit (small ranges only) | O(end - start) | O(C) |
| Bookings plus double-booked lists | O(n) | O(n): fewer than n double-booked stretches |
| Sweep with a sorted map | O(n) plus O(log n) to insert | O(n) |
| Sweep with dict and sorted() | O(n log n) | O(n) |
| Segment tree with lazy updates | O(log C) | O(n log C) nodes |
Why does the double list stay small? Each entry is one overlapping pair of accepted bookings, and no three accepted bookings share a moment. Intervals without a triple overlap can only chain together like links, never form a triangle of mutual overlaps, so n accepted bookings produce at most n - 1 overlapping pairs. The random tests for this page confirmed the bound. The cost that does grow is time: n calls each scanning O(n) entries is O(n²) overall.
Edge cases
- Bookings that only touch at an endpoint never overlap under half-open rules.
- A rejected booking must not leave anything behind; book the same interval twice more after a rejection and check the answers are unchanged.
- The same interval booked twice is fine; a third copy is rejected.
- A new booking that overlaps two existing ones which do not overlap each other must be accepted.
- A booking that fully contains a double-booked stretch is rejected even if its ends are outside every other booking.
Common mistakes
- Counting how many bookings the new one overlaps and rejecting at two. Overlapping two bookings is not a triple booking unless they overlap each other at the same moment.
- Adding to the double list before the rejection check is complete, so a false call still changes state.
- Using <= in the overlap test, which treats [10, 20) and [20, 30) as overlapping.
- In the sweep, forgetting to undo the +1 and -1 on rejection.
- Walking the sweep with the current booking's own changes missing, so the count never includes the new interval.
How to explain it out loud
Fictional example
- Candidate
- A moment becomes triple-booked only if it is already double-booked and the new interval covers it. So I keep the double-booked stretches separately, and the check is just whether the new interval overlaps any of them.
- Candidate
- If it passes, the new interval's overlaps with existing bookings are exactly the new double-booked stretches. I add those and then the booking itself. Nothing is written before the check, so a rejection changes nothing.
- Interviewer
- What if I want at most k overlaps?
- Candidate
- Then I would switch to a sweep: plus one at starts, minus one at ends, walk in order, reject if the running count reaches k plus one and roll back the two changes.
Related problems
Interval List Intersections is the overlap formula on its own, applied to two sorted lists. Range Module is another interval design class, but it keeps a merged set of disjoint ranges instead of counting depth. Employee Free Time uses a running max end where this page uses a running count.
Practicing with Natively
Design questions like this one are graded on the reasoning you say aloud as much as on the class you write. When you run a practice round on Mac or Windows, Natively transcribes your explanation, and after you have committed to your own design it can read the prompt from a screenshot and suggest an alternative to weigh, such as the sweep. Review the transcript for whether you stated the half-open rule before coding. Details on the AI interview assistant.
Questions people ask
How do you solve My Calendar II?
Store accepted bookings and the stretches already double-booked. Reject a new booking if it overlaps any double-booked stretch; otherwise add its overlaps with existing bookings to the double list and accept it.
What is the time complexity of My Calendar II?
O(n) per booking with the two-list method, so O(n squared) over n calls. A sweep with a sorted map is also O(n) per call; a segment tree gets O(log C) for a time range of size C.
Why not reject when a booking overlaps two others?
The two existing bookings might not overlap each other where the new one lies. A triple booking needs one moment covered by all three, which is what the double-booked list tracks.
Are My Calendar intervals inclusive?
No. They are half-open, [start, end), so [10, 20) and [20, 30) do not overlap. Use start < other_end and other_start < end.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
