@@ -22,3 +22,54 @@ Return the updated list of intervals.
2222
2323![ Example 1] ( ./images/examples/insert_interval_example_1.png )
2424![ Example 2] ( ./images/examples/insert_interval_example_2.png )
25+
26+ ## Solution
27+
28+ We first want to create a new list merged to store the merged intervals we will return at the end.
29+
30+ This solution operates in 3 phases:
31+ 1 . Add all the intervals ending before newInterval starts to merged.
32+ 2 . Merge all overlapping intervals with newInterval and add that merged interval to merged.
33+ 3 . Add all the intervals starting after newInterval to merged.
34+
35+ ### Phase 1
36+
37+ In this phase, we add all the intervals that end before newInterval starts to merged. This involves iterating through the
38+ intervals list until the current interval no longer ends before newInterval starts (i.e. intervals[ i] [ 1 ] >= newInterval[ 0] ).
39+
40+ ![ Solution 1] ( ./images/solutions/insert_interval_solution_1.png )
41+ ![ Solution 2] ( ./images/solutions/insert_interval_solution_2.png )
42+
43+ ### Phase 2
44+
45+ In this phase, we merge all the intervals that overlap with newInterval together into a single interval by updating
46+ newInterval to be the minimum start and maximum end of all the overlapping intervals. This involves iterating through
47+ the intervals list until the current interval starts after newInterval ends (i.e. intervals[ i] [ 0 ] > newInterval[ 1] ).
48+ When that condition is met, we add newInterval to merged and move onto phase 3.
49+
50+ ![ Solution 3] ( ./images/solutions/insert_interval_solution_3.png )
51+ ![ Solution 4] ( ./images/solutions/insert_interval_solution_4.png )
52+ ![ Solution 5] ( ./images/solutions/insert_interval_solution_5.png )
53+ ![ Solution 6] ( ./images/solutions/insert_interval_solution_6.png )
54+ ![ Solution 7] ( ./images/solutions/insert_interval_solution_7.png )
55+
56+ ### Phase 3
57+
58+ Phase 3 involves adding all the intervals starting after newInterval to merged. This involves iterating through the
59+ intervals list until the end of the list, and adding each interval to merged.
60+
61+ After completing these 3 phases, we return merged as the final result.
62+
63+ ![ Solution 8] ( ./images/solutions/insert_interval_solution_8.png )
64+ ![ Solution 9] ( ./images/solutions/insert_interval_solution_9.png )
65+ ![ Solution 10] ( ./images/solutions/insert_interval_solution_10.png )
66+
67+ ### Complexity Analysis
68+
69+ #### Time Complexity
70+
71+ O(n) where n is the number of intervals. We iterate through all intervals once to merge them.
72+
73+ #### Space Complexity
74+
75+ O(n) where n is the number of intervals. We need space for the merged output array.
0 commit comments