Last active
April 15, 2022 21:40
-
-
Save Turskyi/28707e88e7cda9aeb26635bab124654d to your computer and use it in GitHub Desktop.
merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
Example 1: | |
Input: intervals = [[1,3],[2,6],[8,10],[15,18]] | |
Output: [[1,6],[8,10],[15,18]] | |
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. | |
Example 2: | |
Input: intervals = [[1,4],[4,5]] | |
Output: [[1,5]] | |
Explanation: Intervals [1,4] and [4,5] are considered overlapping. | |
* */ | |
fun merge(intervals: Array<IntArray>): Array<IntArray> { | |
if (intervals.size <= 1) { | |
return intervals | |
} | |
// first element determines the start of the interval | |
// later, it'll be used to determine when to create a new result item | |
intervals.sortBy { it.first() } // here's the time complexity, O(nlogn) | |
val result: MutableList<IntArray> = mutableListOf() // necessary, minimal space complexity to return result | |
var head: IntArray = intervals.first() // the interval we're editing the end value | |
for (i in 1 until intervals.size) { | |
val curr: IntArray = intervals[i] | |
if (head.last() >= curr.first()) { // grow interval | |
head[1] = Math.max(head.last(), curr.last()) | |
} else { // create new interval | |
result.add(head) | |
head = curr | |
} | |
} | |
result.add(head) // don't forget the greatest one | |
return result.toTypedArray() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment