Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the maximum number of intervals from [[1,5],[2,6],[4,8],[7,9]] that contain a common point? Run the sweep code.

Problem: What is the maximum number of intervals from [[1,5],[2,6],[4,8],[7,9]] that contain a common point? Run the sweep code.
iv = [(1, 5), (2, 6), (4, 8), (7, 9)]
ev = sorted([(s, 1) for s, e in iv] + [(e + 1, -1) for s, e in iv])
c = best = 0
for t, d in ev:
    c += d
    best = max(best, c)
print(best)
What is printed?
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 5

Correct answer: C. 3

Closing an interval at e + 1 with a negative event keeps closed intervals correct, and the peak overlap is the answer.

More Coding Interview Problems questions

Exams that ask this topic