File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity: O(n)
2+ // Space complexity: O(n)
3+
4+ /**
5+ * @param {number[][] } intervals
6+ * @param {number[] } newInterval
7+ * @return {number[][] }
8+ */
9+ var insert = function ( intervals , newInterval ) {
10+ // 1. Insert newInterval
11+ const candidates = [ ] ;
12+ let inserted = false ;
13+
14+ if ( intervals . length === 0 ) {
15+ candidates . push ( newInterval ) ;
16+ }
17+
18+ for ( const [ start , end ] of intervals ) {
19+ const [ newStart , newEnd ] = newInterval ;
20+
21+ if ( ! inserted ) {
22+ if ( newStart <= start ) {
23+ candidates . push ( [ newStart , newEnd ] ) ;
24+ inserted = true ;
25+ }
26+ }
27+
28+ candidates . push ( [ start , end ] ) ;
29+ }
30+
31+ if ( ! inserted ) {
32+ candidates . push ( newInterval ) ;
33+ }
34+
35+ // 2. Merge if needed
36+
37+ const answer = [ ] ;
38+
39+ for ( const [ start , end ] of candidates ) {
40+ if ( answer . length === 0 ) {
41+ answer . push ( [ start , end ] ) ;
42+ continue ;
43+ }
44+
45+ const [ compareStart , compareEnd ] = answer . at ( - 1 ) ;
46+
47+ if ( compareEnd >= start ) {
48+ answer . pop ( ) ;
49+ answer . push ( [ Math . min ( start , compareStart ) , Math . max ( end , compareEnd ) ] ) ;
50+ continue ;
51+ }
52+
53+ answer . push ( [ start , end ] ) ;
54+ }
55+
56+ return answer ;
57+ } ;
You can’t perform that action at this time.
0 commit comments