My Calendar I solution explained

My Calendar I asks you to build a calendar class whose book method accepts a time range only if it does not overlap any range accepted earlier, returning true and storing it, or false and changing nothing. Two half-open ranges clash when each one starts before the other ends. Scanning every stored booking works in O(n) per call; keeping bookings sorted lets you check only the two neighbors of the new range, which is O(log n) per call with a balanced ordered map.

By Published 9 min read

The problem in plain words

Write a class that stands in for a personal calendar. It starts empty. Each call to book(start, end) asks for the time from start up to, but not including, end. If that time does not share any moment with a booking the calendar already holds, store it and return true. If it does, return false and leave the calendar exactly as it was. Refused requests are forgotten; they never block later ones.

One calendar, seven requests in order (written for this page)
RequestResultReason
book(9, 12)trueThe calendar is empty
book(11, 14)false11 to 12 is already taken
book(12, 15)trueStarts exactly when 9 to 12 ends, so nothing is shared
book(5, 9)trueEnds exactly when 9 to 12 starts
book(8, 10)falseClips the end of 5 to 9 and the start of 9 to 12
book(15, 16)trueSits right after 12 to 15
book(3, 20)falseSwallows every booking so far
One calendar, seven requests in order (written for this page). Scroll sideways on a small screen.

The last request is the one that catches weak overlap tests. Neither 3 nor 20 falls inside any stored booking, yet the request covers all of them. A correct test has to catch containment in both directions.

What the interviewer is looking for

This problem checks two things. First, can you write the overlap condition from memory and defend it, including the touching-ends case and the case where one range swallows another? Second, once the simple version works, do you see that an ordered structure lets you inspect only two neighbors, and can you be honest about what that structure costs in your language? Many candidates claim O(log n) for a sorted Python list and get caught on the insert. Saying the real cost unprompted reads as strong.

The overlap test

It is easier to define when two half-open ranges do not clash: one of them ends at or before the other starts. That is e1 <= s2 or e2 <= s1. Negate it and you get the overlap test, s1 < e2 and s2 < e1. This single line covers partial overlap on either side, one range inside the other, and identical ranges. Touching ends, such as [9, 12) and [12, 15), fail the strict comparison and are allowed, which is what you want for calendar slots.

Simple version: compare with every booking

class CalendarSlow:
    def __init__(self):
        self.booked = []

    def book(self, start, end):
        for s, e in self.booked:
            if start < e and s < end:   # half-open ranges overlap
                return False
        self.booked.append((start, end))
        return True
Python: keep a plain list and test the new range against each stored one

Each call is O(k), where k is how many bookings have been accepted so far, so n calls cost O(n²) in the worst case. For the small inputs this problem usually comes with, that is enough to pass, and many interviewers are happy if you write this first and then talk through the improvement. It also serves as the reference the faster versions below were tested against.

Faster: look only at the two neighbors

Accepted bookings never overlap each other, so if you sort them by start time, their end times are sorted too. A new range can only clash with the booking that starts just before it or the booking that starts just after it. Anything further left ended before the left neighbor started; anything further right starts after the right neighbor. So: find where the new start would go, check that the left neighbor ends by the new start, check that the right neighbor starts no earlier than the new end, and insert.

from bisect import bisect_right

class Calendar:
    def __init__(self):
        self.starts = []   # sorted, and no two bookings overlap,
        self.ends = []     # so the ends are sorted in the same order

    def book(self, start, end):
        i = bisect_right(self.starts, start)
        if i > 0 and self.ends[i - 1] > start:
            return False   # the booking just before runs into us
        if i < len(self.starts) and self.starts[i] < end:
            return False   # we run into the booking just after
        self.starts.insert(i, start)
        self.ends.insert(i, end)
        return True
Python: binary search with bisect over two parallel sorted lists

If the new start equals an existing start, bisect_right places it after that booking, and the left check catches the clash because every stored booking has a positive length. The search is O(log k). The two insert calls shift elements, so they are O(k) in the worst case. In practice that shift is a fast memory move, but in an interview you should say it plainly: this version is O(k) per call in theory, with a much smaller constant than the scan.

class Calendar {
  constructor() {
    this.slots = []; // [start, end] pairs kept sorted by start
  }

  book(start, end) {
    // Binary search: i = number of bookings whose start is <= start.
    let lo = 0;
    let hi = this.slots.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (this.slots[mid][0] <= start) lo = mid + 1;
      else hi = mid;
    }
    const before = this.slots[lo - 1];
    const after = this.slots[lo];
    if (before && before[1] > start) return false;
    if (after && after[0] < end) return false;
    this.slots.splice(lo, 0, [start, end]);
    return true;
  }
}
JavaScript: the same idea with a hand-written binary search and splice

JavaScript has no ordered map in its standard library, so splice carries the same O(k) insert cost as the Python list. Reading slots[-1] when lo is 0 returns undefined, which the before && check handles.

#include <iterator>
#include <map>

class Calendar {
    std::map<int, int> slots;  // start -> end, ordered by start

public:
    bool book(int start, int end) {
        auto after = slots.lower_bound(start);  // first start >= start
        if (after != slots.end() && after->first < end) return false;
        if (after != slots.begin() && std::prev(after)->second > start) return false;
        slots[start] = end;
        return true;
    }
};
C++: std::map is a balanced tree, so search and insert are both O(log k)

Here lower_bound returns the first booking whose start is at least the new start, so an equal start lands on the right side and fails the after check. The left neighbor is the element just before it. Java's TreeMap with floorKey and ceilingKey follows the same plan; it was not run for this page.

Cost of each approach

k bookings already accepted; n calls in total
ApproachPer callAll n callsSpace
Scan every bookingO(k)O(n²)O(n)
Sorted Python list or JavaScript arrayO(log k) search, O(k) insertO(n²) worst case, fast in practiceO(n)
Balanced tree (C++ std::map, Java TreeMap)O(log k)O(n log n)O(n)
k bookings already accepted; n calls in total. Scroll sideways on a small screen.

Edge cases to test

  • The first booking on an empty calendar: always accepted.
  • A request that ends exactly when a booking starts, or starts exactly when one ends: accepted.
  • A request identical to a stored booking: refused.
  • A request that sits entirely inside a stored booking, and one that covers a stored booking entirely: both refused.
  • A refused request followed by one that only clashes with the refused range: accepted, since refused ranges are never stored.
  • Requests that arrive in descending order of start, which keeps inserting at the front of an array.

Mistakes that cost points

  • Checking only whether the new start or end falls inside a stored range. That misses a new range that covers a stored one completely.
  • Using <= in the overlap test, which wrongly refuses back-to-back meetings.
  • Storing the request before checking it, or storing it even when refusing.
  • Checking only one neighbor in the sorted version. You need both the booking before and the booking after.
  • Claiming O(log n) per call for a sorted list or array without mentioning the insert.

Follow-up questions

  • Allow two bookings to overlap, but never three. Keep two lists: every accepted booking, and the overlaps between pairs of them. Refuse a request that touches any stored overlap; otherwise record its overlap with each accepted booking and accept it. That is O(k) per call and is the usual answer to the second version of this problem. A short Python sketch of it was checked against a brute-force counter on random requests, but it is not printed here.
  • Report the most bookings that overlap at any moment. Accept everything and keep a count of +1 at each start and -1 at each end in an ordered map, then sweep for the peak. It is the same running-total idea as Car Pooling.
  • Cancel a booking. With the ordered map, erase by start time in O(log k). With parallel lists, find it by binary search and remove it from both.
  • Find the first free slot of a given length after time t. Walk the sorted bookings from t and look at the gaps between neighbors.

How to explain it out loud

Fictional example

Moving from the scan to the neighbors
Candidate
Two ranges are fine together if one ends before the other starts. Flip that and the clash test is: my start is before your end, and your start is before my end.
Candidate
I'll store accepted bookings in a list and test each new one against all of them. That's linear per call.
Interviewer
What if there are a lot of calls?
Candidate
Accepted bookings never overlap, so sorted by start they're also sorted by end. A new range can only clash with its two neighbors, so I binary search for its spot and check both.
Candidate
In Python, the insert into a list still shifts elements, so it's linear in theory. A balanced tree like a C++ map gets the whole thing to log time.

Merge Intervals works on all ranges at once instead of one at a time, and it explains the touching-ends question from the other side. Car Pooling asks how full a timeline gets, which is the counting follow-up above in disguise. Two more problems from the same set test other skills: Design Twitter is another class you build method by method, and Detonate the Maximum Bombs is a search over a graph you construct yourself.

Rehearsing class design questions with Natively

Class design problems tend to be judged on how you narrate each method, not only on whether it compiles. In a practice run, Natively for Mac and Windows can capture the method signatures from a screenshot, suggest the sorted-neighbors approach in whichever language you pick, and transcribe what you say, so you can check afterward whether you mentioned the insert cost before being asked. The LeetCode practice helper page has more on how that works.

Questions people ask

How do you solve My Calendar I?

Store accepted bookings and refuse any request that overlaps one of them. The quick version scans every booking. The faster one keeps bookings sorted by start and checks only the booking just before and just after the new range.

How do you check if two time ranges overlap?

For half-open ranges [s1, e1) and [s2, e2), they overlap when s1 < e2 and s2 < e1. Ranges that only touch at an end do not overlap.

What is the time complexity of My Calendar I?

Scanning is O(k) per call and O(n²) overall. A balanced ordered map such as C++ std::map gives O(log k) per call. A sorted Python list or JavaScript array searches in O(log k) but inserts in O(k).

Can a booking start exactly when another ends?

Yes. Bookings are half-open, so [9, 12) and [12, 15) share no moment and both are accepted.

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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP