Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals and return an array of the non-overlapping intervals that cover all the intervals in the input.
[[1,3],[2,6],[8,10],[15,18]][[1,6],[8,10],[15,18]]startcurr[0] > last[1] → no overlap, add curr as newlast[1] = max(last[1], curr[1])After sorting by start, any interval that overlaps with the last merged interval must have curr.start ≤ last.end. Extending last.end captures the full overlap. Non-overlapping intervals start after last.end, so we add them fresh.
Comparing every pair of intervals, and repeating until nothing changes, is O(n²) or worse. After sorting by start, overlapping intervals sit next to each other.
Sort the intervals by start. Walk through them, and compare each one with the last merged interval. If it starts before that one ends, extend the end, otherwise start a new interval.
Sort by start, then merge with the last interval only. Overlap means the next start is at most the current end.
Run the animation above on your own input, or watch the 1:23 video explanation of Merge Intervals with a dry run and Java code.