Problem Statement
When multiple users try to book the same resource (like a hotel room or a meeting slot) at the same time, conflicts occur. Without proper handling, double bookings happen, causing customer frustration and operational chaos.
This diagram shows two users attempting to book the same resource. The booking server checks availability and locks the resource to prevent conflicts.
### Before: No conflict resolution class BookingSystem: def __init__(self): self.bookings = {} def book(self, resource_id, time_slot): if (resource_id, time_slot) in self.bookings: return False # Double booking possible but not prevented self.bookings[(resource_id, time_slot)] = True return True ### After: With locking to prevent conflicts import threading class BookingSystem: def __init__(self): self.bookings = {} self.locks = {} self.global_lock = threading.Lock() def book(self, resource_id, time_slot): key = (resource_id, time_slot) with self.global_lock: if key not in self.locks: self.locks[key] = threading.Lock() lock = self.locks[key] with lock: if key in self.bookings: return False # Conflict detected self.bookings[key] = True return True
(start1, end1) and (start2, end2) overlap?start1 < end2 and start2 < end1 correctly detects overlap.[(10, 12), (14, 16), (18, 20)], what will be the result of checking a new booking (12, 14) for conflict using the overlap condition start1 < end2 and start2 < end1?def is_conflict(new_start, new_end, existing_bookings):
for start, end in existing_bookings:
if new_start <= end and new_end >= start:
return True
return Falsenew_start <= end and new_end >= start includes cases where bookings just touch at edges, causing false conflicts.new_start < end and new_end > start to detect true overlaps only.Pass the test and this pattern moves unknown