Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count number of intervals that is totally contained inside other intervals in Python
Suppose we have a list of intervals where each interval[i] has [start, end] values. We need to find the number of intervals that are completely contained inside other intervals. If an interval is contained by multiple other intervals, it should only be counted once. An interval [s0, e0] is inside another interval [s1, e1] when s1 ? s0 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] is inside [2, 6] and [5, 5] is inside [4, 7].
Algorithm
To solve this problem, we follow these steps ?
- If intervals list is empty, return 0
- Sort the intervals list based on start time; when start times are same, sort in decreasing order of end time
- Initialize end_mx := -infinity and ans := 0
- For each (start, end) pair in intervals:
- If end ? end_mx, then increment ans (interval is contained)
- Update 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
# Sort by start time, then by end time in descending order
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))
The output of the above code is ?
2
How It Works
The algorithm works by sorting intervals and tracking the maximum end time seen so far. When we encounter an interval whose end time is less than or equal to the current maximum end time, it means this interval is contained within a previously processed interval.
For our example:
- After sorting: [[2, 6], [3, 4], [4, 7], [5, 5]]
- Process [2, 6]: end_mx = 6
- Process [3, 4]: 4 ? 6, so count it (contained in [2, 6])
- Process [4, 7]: 7 > 6, so end_mx = 7
- Process [5, 5]: 5 ? 7, so count it (contained in [4, 7])
Conclusion
This solution efficiently counts contained intervals in O(n log n) time by sorting intervals and tracking maximum end times. The key insight is that after sorting, any interval with an end time less than or equal to the current maximum is guaranteed to be contained within a previous interval.
