Data Structures & AlgorithmsHardProduct Company SDE · greedy OA

Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is allowed)? Run the greedy code on [[1,2],[2,3],[3,4],[1,3]].

Problem: What is the minimum number of intervals to remove so that the rest are pairwise non-overlapping (touching at an endpoint is allowed)? Run the greedy code on [[1,2],[2,3],[3,4],[1,3]].
def rem(iv):
    iv = sorted(iv, key=lambda x: x[1])
    end = float('-inf')
    keep = 0
    for s, e in iv:
        if s >= end:
            keep += 1
            end = e
    return len(iv) - keep
print(rem([[1, 2], [2, 3], [3, 4], [1, 3]]))
What is printed?
  1. A. 0
  2. B. 2
  3. C. 1
  4. D. 3

Correct answer: C. 1

The greedy keeps the intervals by earliest end, keeping [1,2], [2,3] and [3,4] and dropping [1,3]. Sorting by start time instead can drop too many intervals.

More Coding Interview Problems questions

Exams that ask this topic