KatInterview

Does a New Booking Collide With Existing Slots?

Greedy & IntervalsAuto-graded · 21 test cases
EasyAuto-gradedGreedy & Intervalsintervalsoverlaphalf-open

Last updated

Decide whether a proposed half-open time slot shares any time with a list of unsorted booked slots, testing overlap logic and correct handling of touching endpoints.

Does a New Booking Collide With Existing Slots?

A scheduling system stores a collection of booked time slots in no particular order. Each slot is a half-open range [start, end): it includes start but excludes end.

A customer now asks for one more slot, called the candidate, also written [start, end). Decide whether the request can be placed without clashing with any existing slot.

Definition of a clash

Two slots [a, b) and [c, d) clash if and only if they share at least one moment in time, which happens exactly when the overlap region [max(a, c), min(b, d)) is non-empty, i.e.

max(a, c) < min(b, d)

Slots that only touch at an endpoint do not clash. For instance, [1, 3) and [3, 5) can coexist.

Task

Implement a function that returns True if the candidate clashes with at least one slot in slots, and False otherwise.

Input

  • slots: a list of existing slots, each given as a pair [start, end] with start < end. The list is unsorted, and the existing slots may overlap each other.
  • candidate: a pair [start, end] with start < end.

Output

  • A boolean: True if the candidate clashes with any existing slot, otherwise False.
  • If slots is empty, the answer is False.

Constraints

  • 0 <= len(slots) <= 10^5
  • -10^9 <= start < end <= 10^9 for every slot, including the candidate
  • Slots are not guaranteed to be sorted or disjoint

Examples

Example 1

Input: has_booking_clash([[1, 4], [6, 10], [12, 15]], [4, 6])

Output: False

Example 2

Input: has_booking_clash([[10, 15], [1, 5], [20, 25]], [4, 7])

Output: True

Hints

Hint 1

Write down what the shared region of two half-open ranges looks like, then decide when that region is empty.

Hint 2

Two slots clash exactly when the larger of the two starts is strictly smaller than the smaller of the two ends. Be careful about strict versus non-strict comparison.

Hint 3

The data is unsorted and you only have one query, so a single pass that stops at the first clash is enough.