Program to count number of intervals that is totally contained inside other intervals in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of intervals. In this list interval[i] has [start, end] values. We have to find the number of intervals are contained by another interval. If there is an interval that is contained by multiple other intervals that should only be counted once. An interval [s0, e0] is inside another interval [s1, e1] when s0 ≤ s1 and e0 ≥ e1.

So, if the input is like intervals = [[2, 6],[3, 4],[4, 7],[5, 5]], then the output will be 2, because [3, 4] and [5, 5] are inside [2, 6] and [4, 7] respectively.

To solve this, we will follow these steps −

  • if intervals list is empty, then
    • return 0
  • sort the intervals list based on start time, when start times are same, sort in decreasing order of end time
  • end_mx := -infinity
  • ans := 0
  • for each (start, end) pair in intervals, do
    • if end <= end_mx, then
      • ans := ans + 1
    • end_mx := maximum of end_mx and end
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(intervals):
   if not intervals:
      return 0

   intervals.sort(key=lambda x: (x[0], -x[1]))

   end_mx = float("-inf")
   ans = 0

   for start, end in intervals:
      if end <= end_mx:
         ans += 1

      end_mx = max(end_mx, end)

   return ans

intervals = [[2, 6],[3, 4],[4, 7],[5, 5]]
print(solve(intervals))

Input

[[2, 6],[3, 4],[4, 7],[5, 5]]

Output

2
raja
Published on 18-Oct-2021 11:55:18
Advertisements