Given two lists each containing N intervals (subset of the number line), each interval with form of a start point and endpoint. How many pairs of these intervals from one list contains intervals from another list?
For example:
If list A is {(1,7), (2,9)}
and list B is {(3,6), (5,8)}
Then the count of pairs where A has an interval that contains an interval in B would be 3 pairs:
(1,7),(3,6)
(2,9)(3,6)
(2,9)(5,8)
The goal is to shoot for O(n log n).
My algorithm currently is to sort by x-coordinate first and take that as one list. Then sort the list by y-coordinate and count the inversions between the two lists. But my question is why does this work? Any insight would be appreciated.
The way I have I'm currently visualizing is in the following geometric fashion (where each intersection of the lines is a count of the num inversion):
Note: I'm not sure how to go about checking inversions in a list of list. Just trying to get an approach that would give O(n log n). If there are any other approaches happy to hear suggestions.