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?
  1. A. 4 4 3
  2. B. 4 3 3
  3. C. 3 4 3
  4. 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

Exams that ask this topic