File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n log n)
2+ // Space Complexity: O(n)
3+
4+ var insert = function ( intervals , newInterval ) {
5+ // append the newInterval to the intervals array
6+ intervals . push ( newInterval ) ;
7+
8+ // sort the intervals array by start time
9+ intervals . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
10+
11+ // to store merged intervals
12+ let result = [ ] ;
13+
14+ // iterate through the sorted intervals array
15+ for ( let i = 0 ; i < intervals . length ; i ++ ) {
16+ // if the result array is empty or the current interval does not overlap with the last interval
17+ if ( result . length === 0 || result [ result . length - 1 ] [ 1 ] < intervals [ i ] [ 0 ] ) {
18+ result . push ( intervals [ i ] ) ; // Add the current interval to the result array
19+ } else {
20+ // if there is an overlap, merge the current interval with the last interval
21+ result [ result . length - 1 ] [ 1 ] = Math . max (
22+ result [ result . length - 1 ] [ 1 ] ,
23+ intervals [ i ] [ 1 ]
24+ ) ;
25+ }
26+ }
27+
28+ // return the final merged intervals
29+ return result ;
30+ } ;
Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n log n)
2+ // Space Complexity: O(n)
3+
4+ var merge = function ( intervals ) {
5+ // sort the intervals by their start time
6+ intervals . sort ( ( a , b ) => a [ 0 ] - b [ 0 ] ) ;
7+
8+ // to manage merged intervals
9+ let stack = [ ] ;
10+
11+ // push the first interval onto the stack
12+ stack . push ( intervals [ 0 ] ) ;
13+
14+ // iterate through the sorted intervals
15+ for ( let i = 1 ; i < intervals . length ; i ++ ) {
16+ // get the top interval from the stack
17+ let top = stack [ stack . length - 1 ] ;
18+
19+ // if the current interval overlaps with the top interval
20+ if ( top [ 1 ] >= intervals [ i ] [ 0 ] ) {
21+ // merge the intervals by updating the end of the top interval
22+ top [ 1 ] = Math . max ( top [ 1 ] , intervals [ i ] [ 1 ] ) ;
23+ } else {
24+ // if there is no overlap, push the current interval onto the stack
25+ stack . push ( intervals [ i ] ) ;
26+ }
27+ }
28+
29+ // return the final merged intervals
30+ return stack ;
31+ } ;
You can’t perform that action at this time.
0 commit comments