You are given a list of intervals, and your task is to count how many of the intervals are nested inside another interval.
An interval consists of the integers . For example, the interval consists of the integers . An interval is nested inside an interval if and . For example, the intervals , and are all nested inside the interval .
For example, for the list the desired answer is , because the intervals and are nested inside another interval. The interval is nested inside the interval , and the interval is nested inside the interval .
In a file intervals.py
, implement the function count_nested
that takes a list of intervals as a parameter and returns the number of nested intervals. You may assume that no two intervals on the list are the same.
You should implement the function so that it runs efficiently even for long lists. The function should finish immediately in the last two test cases of the code template too.
import random def count_nested(intervals): # TODO if __name__ == "__main__": print(count_nested([])) # 0 print(count_nested([(1, 2)])) # 0 print(count_nested([(1, 2), (3, 4)])) # 0 print(count_nested([(1, 3), (2, 4)])) # 0 print(count_nested([(1, 4), (2, 3)])) # 1 print(count_nested([(1, 4), (1, 3)])) # 1 print(count_nested([(1, 4), (2, 4)])) # 1 print(count_nested([(1, 1), (1, 2), (1, 3)])) # 2 print(count_nested([(1, 6), (2, 5), (3, 4)])) # 2 print(count_nested([(1, 4), (2, 5), (3, 6)])) # 0 intervals = [(x+1, x+3) for x in range(10**5)] random.shuffle(intervals) print(count_nested(intervals)) # 0 intervals = [(x+1, 2*10**5-x) for x in range(10**5)] random.shuffle(intervals) print(count_nested(intervals)) # 99999