Merge overlapping intervals using a greedy approach with sorting
Given: An array of intervals where intervals[i] = [starti, endi]
Task: Merge all overlapping intervals and return an array of non-overlapping intervals that cover all intervals in the input.
Example:
[[1,3],[2,6],[8,10],[15,18]] → Output: [[1,6],[8,10],[15,18]][[1,4],[4,5]] → Output: [[1,5]]fun merge(intervals: Array<IntArray>): List<IntArray> {
intervals.sortBy { it[0] }
val merged = mutableListOf(intervals[0])
for (i in 1 until intervals.size) {
val current = intervals[i]
val last = merged.last()
if (current[0] <= last[1]) {
last[1] = maxOf(last[1], current[1])
} else {
merged.add(current)
}
}
return merged
}
After sorting intervals by start time, we only need to check if the current interval overlaps with the last merged interval. If they overlap (current start ≤ last end), we extend the last interval. Otherwise, we add the current interval as a new separate interval.