File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ fun insert (intervals : Array <IntArray >, newInterval : IntArray ): Array <IntArray > {
3+ val result = mutableListOf<IntArray >()
4+ var currentStart = newInterval[0 ]
5+ var currentEnd = newInterval[1 ]
6+ var isAdded = false
7+
8+ // TC: O(n)
9+ // SC: O(n)
10+ for (interval in intervals){
11+ if (isAdded) {
12+ result.add(interval)
13+ } else {
14+ if (interval[1 ] < currentStart){ // new interval is after the current interval
15+ result.add(interval) // just add the interval without any changes
16+ }
17+ else if (interval[0 ] > currentEnd){ // new interval is before the current interval
18+ result.add(intArrayOf(currentStart, currentEnd))
19+ result.add(interval)
20+ isAdded = true
21+ }
22+ else { // intervals overlap, merge them
23+ currentStart = minOf(interval[0 ], currentStart)
24+ currentEnd = maxOf(interval[1 ], currentEnd)
25+ }
26+ }
27+ }
28+
29+ // If new interval wasn't added yet, add it now
30+ if (! isAdded) {
31+ result.add(intArrayOf(currentStart, currentEnd))
32+ }
33+
34+ return result.toTypedArray()
35+ }
36+ }
You can’t perform that action at this time.
0 commit comments