← Home

57. Insert Interval

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
57

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 57. Insert Interval, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 32 ms, faster than 70.39% of C++ online submissions for Insert Interval.
02//Memory Usage: 17.1 MB, less than 42.94% of C++ online submissions for Insert Interval.
03class Solution {
04public:
05    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
06        vector<int> start_dummy = {-1, newInterval[0]};
07        vector<int> end_dummy = {newInterval[1], -1};
08        
09        //the smallest interval with end >= start_dummy[1]
10        auto it1 = lower_bound(intervals.begin(), intervals.end(),
11          start_dummy,
12          [](const vector<int>& a, const vector<int>& b){
13              return a[1] < b[1];
14          });
15        
16        if(it1 == intervals.end()){
17            intervals.push_back(newInterval);
18            return intervals;
19        }
20        // cout << (*it1)[0] << ", " << (*it1)[1] << endl;
21        
22        //the smallest interval with start > end_dummy[0]
23        auto it2 = upper_bound(intervals.begin(), intervals.end(),
24          end_dummy,
25          [](const vector<int>& a, const vector<int>& b){
26              return a[0] < b[0];
27          });
28        if(it2 == intervals.begin()){
29            intervals.insert(intervals.begin(), newInterval);
30            return intervals;
31        }
32        
33        //the largest interval with start <= end_dummy[0]
34        it2 = prev(it2);
35        
36        // cout << (*it2)[0] << ", " << (*it2)[1] << endl;
37        
38        if(it1 == it2){
39            *it1 = {min((*it1)[0], newInterval[0]),
40                max((*it1)[1], newInterval[1])};
41        }else if(it1 < it2){
42            vector<int> insertInterval = {
43                min((*it1)[0], newInterval[0]),
44                max((*it2)[1], newInterval[1])
45            };
46            *it1 = insertInterval;
47            //erase [it1+1, it2]
48            intervals.erase(it1+1, it2+1);
49        }else{
50            //it2 < it1
51            //newInterval should be insert btw it2 and it1
52            intervals.insert(it1, newInterval);
53        }
54        
55        return intervals;
56    }
57};
58
59//https://leetcode.com/problems/insert-interval/discuss/21602/Short-and-straight-forward-Java-solution
60//Runtime: 28 ms, faster than 87.60% of C++ online submissions for Insert Interval.
61//Memory Usage: 16.9 MB, less than 89.34% of C++ online submissions for Insert Interval.
62class Solution {
63public:
64    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
65        vector<vector<int>> ans;
66        int i = 0, n = intervals.size();
67        
68        //smaller, no intersection
69        while(i < n && intervals[i][1] < newInterval[0]){
70            ans.push_back(intervals[i]);
71            ++i;
72        }
73        
74        //having intersection
75        int start = newInterval[0], end = newInterval[1];
76        while(i < n && intervals[i][0] <= end){
77            start = min(intervals[i][0], start);
78            end = max(intervals[i][1], end);
79            ++i;
80        }
81        
82        ans.push_back({start, end});
83        
84        while(i < n){
85            ans.push_back(intervals[i]);
86            ++i;
87        }
88        
89        return ans;
90    }
91};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.