
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count number of intervals that is totally contained inside other intervals in Python
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
- if end <= end_mx, then
- 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
- Related Articles
- Program to count number of intervals which are intersecting at given point in Python
- Program to find intervals that do not intersect the cut interval in Python
- Merge Intervals in Python
- C++ Program to Display Armstrong Number Between Two Intervals
- Java Program to Display Armstrong Number Between Two Intervals
- Swift Program to Display Armstrong Number Between Two Intervals
- Golang Program to Display Armstrong Number Between Two Intervals
- Program to find contiguous intervals of a unique array in Python
- Count the number of intervals in which a given value lies in C++
- Program to find intervals by merging target interval in Python
- Program to find partition array into disjoint intervals in Python
- Find Intersecting Intervals in Python
- Most Frequent Number in Intervals in C++
- Program to find total unique duration from a list of intervals in Python
- Program to find minimum number of intervals to be removed to remove overlaps in C++

Advertisements