===== ISTEM =====
Solve the following programming task.

TASK: Merge Intervals

Write a function 'merge_intervals(intervals)' that takes a list of closed intervals that may overlap (e.g. [[1,3],[2,6],[8,10],[15,18]]) and returns a new list with the overlapping ones merged.

STARTER CODE (python):
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    # Write your code here
    pass


RULES:
- Keep the function name and signature EXACTLY as given.
- Return working code only. No explanations.
- Put the code in a single ``` block.
- Try to solve it first. If you genuinely cannot, write only this single
  line instead of producing faulty code: CANNOT_SOLVE

===== HAM YANIT =====
```python
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    if not intervals:
        return []

    # Sort by start of each interval
    intervals.sort(key=lambda x: x[0])

    merged: list[list[int]] = []
    current = intervals[0]

    for interval in intervals[1:]:
        # If current interval overlaps with the next one
        if interval[0] <= current[1]:
            # Merge by extending the end if needed
            current[1] = max(current[1], interval[1])
        else:
            # No overlap, push current and start new
            merged.append(current)
            current = interval

    # Append the last interval
    merged.append(current)
    return merged
```
