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?- A. 2 2
- B. 3 3
- C. 3 2
- 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
- Problem: Total length covered by a set of intervals, and the length covered by EXACTLY one interval, using coordinate compression and a…
- Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median…
- Problem: Minimum cuts to split a string into palindromes: interval DP (pal table + cut array) versus the greedy 'always take the longest…
- Problem: Count Hamiltonian paths (visit every junction exactly once) in a 5-vertex road graph with bitmask DP over (visited set, current…
- Problem: a judge checks your rolling-hash solution with hash(s) = Σ s[i]·Bⁱ computed in unsigned 64-bit arithmetic (implicitly modulo…
- Problem: n ≤ 2·10⁵ values and q ≤ 2·10⁵ offline queries 'how many DISTINCT values are in a[l..r]?' (time limit 2 s). Which approach is…