Data Structures & AlgorithmsVery hardProduct company OA

Problem: Peak number of simultaneous bookings with a sweep line. In the first call intervals are CLOSED [s, e] (a booking ending at 3 and one starting at 3 overlap); in the second they are half-open [s, e). Event ties are broken by the type code.

Problem: Peak number of simultaneous bookings with a sweep line. In the first call intervals are CLOSED [s, e] (a booking ending at 3 and one starting at 3 overlap); in the second they are half-open [s, e). Event ties are broken by the type code.
def peak(iv, closed):
    ev = []
    for s, e in iv:
        ev.append((s, 1))
        ev.append((e, 2) if closed else (e, 0))
    ev.sort()
    cur = best = 0
    for _, typ in ev:
        cur += 1 if typ == 1 else -1
        best = max(best, cur)
    return best
iv = [(1, 3), (3, 5), (5, 7), (2, 6), (6, 8), (7, 9)]
print(peak(iv, True), peak(iv, False))
What is printed?
  1. A. 2 2
  2. B. 3 3
  3. C. 3 2
  4. D. 4 2

Correct answer: C. 3 2

Sorting (time, type) with start = 1 and end = 2 processes starts before ends at the same time, so touching closed intervals count as overlapping: at time 3, (1, 3), (2, 6) and (3, 5) are all active → 3. With end = 0 the end is processed first, so touching intervals do not overlap → peak 2. Getting this tie rule wrong is the classic off-by-one in meeting-room and platform problems. O(n log n).

More Coding Interview Problems questions

Exams that ask this topic