Merge Intervals in Python

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        # Step 1: Sort the intervals based on the starting point of each interval.
        intervals.sort(key=lambda x: x[0])

        # The merged list to store the merged intervals
        merged = []

        for interval in intervals:
            # If the merged list is empty or the current interval does not overlap with the previous,
            # append it to the merged list.
            if not merged or merged[-1][1] < interval[0]:
                merged.append(interval)
            else:
                # There is an overlap, merge the current interval with the previous one.
                # We do this by updating the end of the last interval in the merged list
                # to the maximum end of the overlapping intervals.
                merged[-1][1] = max(merged[-1][1], interval[1])

        return merged

PrevNext