Skip to content

Commit 77792ed

Browse files
authored
Merge pull request #2108 from a93a/main
Create 0057-insert-interval.kt
2 parents 6209ad0 + 1b139e0 commit 77792ed

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: kotlin/0057-insert-interval.kt

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
3+
val res = ArrayList<IntArray>()
4+
var added = false
5+
var index = 0
6+
for(i in 0 until intervals.size){
7+
val interval = intervals[i]
8+
if(newInterval[1] < interval[0]){ //no more overlapping intervals
9+
res.add(newInterval)
10+
added = true
11+
break
12+
}else if(newInterval[0] > interval[1]){ //non overlapping
13+
res.add(interval)
14+
}else{ //overlapping, update the newinterval accordingly
15+
newInterval[0] = minOf(newInterval[0],interval[0])
16+
newInterval[1] = maxOf(newInterval[1],interval[1])
17+
}
18+
index++
19+
}
20+
if(index < intervals.size){ // add all the leftover intervals (after the break)
21+
for(i in index until intervals.size)
22+
res.add(intervals[i])
23+
}
24+
if(added == false) // takes care of (1) Empty intervals array or 1-sized array with overlapping newinterval
25+
res.add(newInterval)
26+
return res.toTypedArray()
27+
}
28+
}

0 commit comments

Comments
 (0)