Merge overlapping intervals in Python - Leetcode 56. Merge Intervals

Problem:
Given a set of intervals in arbitrary order, merge overlapping intervals to produce a list of intervals which are mutually exclusive.

Eg:
 [ [1,4], [1,5] ] --> [ [1,5] ]
[[6,8], [1,9], [2,4], [4,7]] -> [ [1, 9] ]

Approach:

This approach to solving the problem borrows the idea of how balanced parentheses are checked. We first flatten the given list of intervals into individual bounds and associate each of them with an integer which signifies whether that bound is lower or an upper bound. We then sort this list according to the starting/ending integer and then the bound i.e for the same starting/ending integer, lower bound should come before the upper bound. We use a stack and keep pushing items onto it as long as the integer represents a lower bound and pop items if it is an upper bound. If at any point of time, the stack gets empty, then we have found one merged interval.

Eg:

[ (6, 8), (1, 9), (2, 4), (4, 7) ]

Step 1: Flatten the list

[ (6, 8), (1, 9), (2, 4), (4, 7) ] -> [(6, 0), (8, 1), (1, 0), (9, 1), (2, 0), (4, 1), (4, 0), (7, 1)]

0/1 of a tuple in the resulting list tells whether it is a lower/upper bound respectively.

Step 2: Sort the flattened list

[(1, 0), (2, 0), (4, 0), (4, 1), (6, 0), (7, 1), (8, 1), (9, 1)]

Step 3: Go through the list item by item and merge as explained above.

Code: