TRT
Sign in
mediumAdvancedLeetCode#ordered map floor and ceiling

My calendar I

Accept a booking only if it overlaps no existing one, by checking its neighbors in an ordered map.

The Runtime Theory Team1 min read
Taught inRed-black treesPro — members onlyA red-black tree colors each node red or black and requires every path from a node down to its leaves to cross the same number of black nodes. That looser rule keeps the height under 2 log₂ n while needing at most two rotations per insert and three per delete.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inbook(10, 20), book(15, 25), book(20, 30)

out[true, false, true]

inbook(5, 10), book(1, 6), book(1, 5)

out[true, false, true]

inbook(0, 1), book(1, 2), book(0, 2)

out[true, true, false]

Implement book(start, end) for half-open intervals [start, end). Add the booking and return true if it doesn't overlap any existing booking; otherwise return false and leave the calendar unchanged.

Before you code

Existing bookings never overlap each other, so sorted by start they are also sorted by end. Which two existing bookings can possibly conflict with a new one?

Hints

  1. Keep bookings in an ordered map from start to end: TreeMap in Java, std::map in C++, SortedDict or a sorted list with bisect in Python.
  2. The new booking fits when the previous booking ends at or before start, and the next booking starts at or after end.
  3. Each book is one floor and one ceiling query: O(log n) with a balanced tree.

Production & complexity notes

When solving My calendar I on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Red-black trees to reinforce the underlying pattern.

What it practices

Floor and ceiling queries on an ordered map, from Red-black trees.

Not started

Sign in to save your learning progress.

Sign in to save