from typing import List


def merge_intervals(intervals: List[List]) -> List[List]:
    """
    LeetCode 59: Merge Intervals
    Given a collection of intervals, merge all overlapping intervals.
    Examples:
        1. [[1, 3], [8, 10], [2, 6], [15, 18]] -> [[1, 6], [8, 10], [15, 18]]
        2. [[1, 4], [4, 5]] -> [[1, 5]]
    """
    if len(intervals) <= 1:
        return intervals
    res = []
    intervals = sorted(intervals)
    first = intervals[0]
    for second in intervals[1:]:
        if first[1] < second[0]:
            res.append(first)
            first = second
        elif first[1] <= second[1]:
            first[1] = second[1]

    res.append(first)
    return res