Merge Intervals
MediumArrays · SortingO(n log n) time · O(n) space
The problem
Given a list of intervals, merge all overlapping ones and return the result.
[[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]Stuck? Open one hint
Overlap is only easy to see when the intervals arrive in a known order.
Show the worked solution
Sort by start. Now an interval can only overlap the one you are currently building, never an earlier one — that is the whole insight.
Walk the sorted list: if the next start is less than or equal to the current end, extend the current end to the maximum of the two. Otherwise close the current interval and start a new one.
Say the real-world version too — this is the same algorithm as merging calendar busy-slots, which is how the question is often framed in a product round.
fun merge(intervals: Array<IntArray>): List<IntArray> {
if (intervals.isEmpty()) return emptyList()
val sorted = intervals.sortedBy { it[0] }
val out = mutableListOf(sorted[0].copyOf())
for (i in 1 until sorted.size) {
val last = out.last()
val cur = sorted[i]
if (cur[0] <= last[1]) last[1] = maxOf(last[1], cur[1])
else out.add(cur.copyOf())
}
return out
}O(n log n) time · O(n) space
