I'm trying to count the number of non-overlapping pairs given a list of intervals.
For example:
[(1, 8), (7, 9), (3, 10), (7, 12), (11, 13), (13, 14), (9, 15)]
There are 8 pairs:
((1, 8), (11, 13))((1, 8), (13, 14))((1, 8), (9, 15))((7, 9), (11, 13))((7, 9), (13, 14))((3, 10), (11, 13))((3, 10), (13, 14))((7, 12), (13, 14))
I can't seem to figure out a better solution other than to just brute force it by comparing everything with virtually everything else, resulting in a O(n^2) solution.
def count_non_overlapping_pairs(intervals): intervals = list(set(intervals)) # deduplicate any intervals intervals.sort(key=lambda x: x[1]) pairs = 0 for i in range(len(intervals)): for j in range(i+1, len(intervals)): if intervals[i][1] < intervals[j][0]: pairs += 1 return pairs
Is there a more optimal solution than this?