Data Structures & AlgorithmsVery hardProduct company OA
Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day. Compare a day sweep with a min-heap of end days, 'sort by end and take the earliest free day', and 'sort by start and take the earliest free day'.
Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day. Compare a day sweep with a min-heap of end days, 'sort by end and take the earliest free day', and 'sort by start and take the earliest free day'.
import heapq
def attend(events):
events.sort(); h = []; i = day = cnt = 0; n = len(events)
while i < n or h:
if not h: day = max(day, events[i][0])
while i < n and events[i][0] <= day: heapq.heappush(h, events[i][1]); i += 1
while h and h[0] < day: heapq.heappop(h)
if h: heapq.heappop(h); cnt += 1; day += 1
return cnt
def by_end(events):
used, cnt = set(), 0
for s, e in sorted(events, key=lambda x: x[1]):
for d in range(s, e + 1):
if d not in used: used.add(d); cnt += 1; break
return cnt
def by_start(events):
used, cnt = set(), 0
for s, e in sorted(events):
for d in range(s, e + 1):
if d not in used: used.add(d); cnt += 1; break
return cnt
ev = [(1, 2), (1, 1), (2, 3), (1, 4), (3, 3), (2, 2)]
print(attend(list(ev)), by_end(ev), by_start(ev))What is printed?- A. 4 4 3
- B. 4 3 3
- C. 3 4 3
- D. 4 4 4
Correct answer: A. 4 4 3
Sweeping days and always serving the open event that ends soonest is an exchange-argument greedy and is optimal: 4 events (days 1, 2, 3, 4). Sorting by end and giving each event its earliest free day is also optimal. Sorting by START fails: (1, 4) is processed early and takes day 3, which the one-day event (3, 3) needed, so only 3 events are attended. The heap version runs in O((n + D) log n) without scanning day ranges.
More Coding Interview Problems questions
- Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph…
- Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?). python…
- Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow)…
- Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k…
- Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x…
- Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]'…