Grokking the Coding Interview: Patterns for Coding Questions

0% completed

My Calendar I (medium)

Problem Statement

Given a 2D array nums of size N x 2.

  • nums[i] = [start<sub>i</sub>, end<sub>i</sub>], where start<sub>i</sub> is the starting time of the event and end<sub>i</sub> is the ending time of the event.

For each nums[i], determine if a requested booking time conflicts with any existing bookings.

Return a boolean array of size N, representing whether the booking can be done in the given time interval.

Examples

  1. Example 1:
    • Input: nums = [[10, 20], [15, 25], [20, 30]]
    • Expected Output: [true, false, true]

.....

.....

.....

Like the course? Get enrolled and start learning!
Sachin Dev S

Sachin Dev S

· 2 years ago

import bisect from typing import List class Solution: def __init__(self): self.bookings = [] def book(self, nums: List[List[int]]) -> List[bool]: results = [] for interval in nums: start, end = interval event = (start, end) # Find the index where the event should be inserted to maintain sorted order idx = bisect.bisect_left(self.bookings, event) # Find lower and higher neighbors lower = self.bookings[idx - 1] if idx > 0 else None higher = self.bookings[idx] if idx < len(self.bookings) else None # Check for overlap with neighboring events if (lower is None or lower[1] <= start) and (higher is None or end <= higher[0]):
Mohammed Dh Abbas

Mohammed Dh Abbas

· 2 years ago

class Solution: def book(self, nums): result = [] # to track the booked times b_start, b_end = float('inf'), float('-inf') for start, end in nums: if start >= b_end or end <= b_start: b_start = min(start, b_start) b_end = max(b_end, end) result.append(True) else: result.append(False) return result
M

mailman14736

· 2 days ago

python implementation is O(N^2) time complexity because you did not implement your own sorted set interface. Same issue as all other solutions in this section. Might be worth showing implementation for a skip list or red black tree.