Skip to content

Create 0057-insert-interval.kt #2108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions kotlin/0057-insert-interval.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
val res = ArrayList<IntArray>()
var added = false
var index = 0
for(i in 0 until intervals.size){
val interval = intervals[i]
if(newInterval[1] < interval[0]){ //no more overlapping intervals
res.add(newInterval)
added = true
break
}else if(newInterval[0] > interval[1]){ //non overlapping
res.add(interval)
}else{ //overlapping, update the newinterval accordingly
newInterval[0] = minOf(newInterval[0],interval[0])
newInterval[1] = maxOf(newInterval[1],interval[1])
}
index++
}
if(index < intervals.size){ // add all the leftover intervals (after the break)
for(i in index until intervals.size)
res.add(intervals[i])
}
if(added == false) // takes care of (1) Empty intervals array or 1-sized array with overlapping newinterval
res.add(newInterval)
return res.toTypedArray()
}
}