Leetcode 56 Solution

This article provides solution to leetcode question 56 (merge-intervals)

https://leetcode.com/problems/merge-intervals

Solution

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        events = []
        for start, end in intervals:
            events.append((start, -1))
            events.append((end, 1))
        events.sort()

        start = 0
        curr = 0

        ans = []
        for i, op in events:
            if op == -1:
                curr += 1
                if curr == 1:
                    start = i
            elif op == 1:
                curr -= 1
                if curr == 0:
                    ans.append((start, i))

        return ans