← Home

56. Merge Intervals

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
stackC++Markdown
56

The trick here is to name the state correctly, then let the implementation follow. For 56. Merge Intervals, the solution in this repository is mainly a stack solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: stack, greedy.

The notes already sitting in the source point us in the right direction:

  • TLE
  • 168 / 169 test cases passed.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are overlap, buildGraph, markComponentDFS, buildComponents, mergeNodes.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

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(build graph) + O(traverse graph) + O(merge) = O(V+E) + O(V+E) +O(V) = O(n^2+n) + O(n^2+n) + O(n) = O(n^2)
  • Space: O(n^2)

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//168 / 169 test cases passed.
03class Solution {
04public:
05    vector<vector<int>> merge(vector<vector<int>>& intervals) {
06        if(intervals.size() < 2) return intervals;
07        
08        sort(intervals.begin(), intervals.end());
09        
10        int i = 1;
11        while(i < intervals.size()){
12            // cout << i << " ";
13            //last end >= current start
14            if(intervals[i-1][1] >= intervals[i][0]){
15                //merge them
16                intervals[i-1][1] = max(intervals[i-1][1], intervals[i][1]);
17                intervals.erase(intervals.begin()+i);
18            }else{
19                i++;
20            }
21        }
22        
23        return intervals;
24    }
25};
26
27//Approach 2: Sorting, Greedy
28//the above method removes merged intervals, this method add unmerged intervals into ans
29//Runtime: 52 ms, faster than 58.81% of C++ online submissions for Merge Intervals.
30//Memory Usage: 14.3 MB, less than 84.61% of C++ online submissions for Merge Intervals.
31//time: O(NlogN), space: O(1) if it's in-place sorting or O(N)
32class Solution {
33public:
34    vector<vector<int>> merge(vector<vector<int>>& intervals) {
35        if(intervals.size() < 2) return intervals;
36        
37        //sort by start point
38        sort(intervals.begin(), intervals.end());
39        
40        vector<vector<int>> ans;
41        
42        for(vector<int>& interval : intervals){
43            if(ans.empty() || ans.back()[1] < interval[0]){
44                ans.push_back(interval);
45            }else{
46                ans[ans.size()-1][1] = max(ans.back()[1], interval[1]);
47            }
48        }
49        
50        return ans;
51    }
52};
53
54//Approach 1: Connected Components
55//TLE
56//168 / 169 test cases passed.
57//time: O(build graph) + O(traverse graph) + O(merge) = O(V+E) + O(V+E) +O(V) = O(n^2+n) + O(n^2+n) + O(n) = O(n^2)
58//space: O(n^2)
59class Solution {
60public:
61    map<vector<int>, vector<vector<int>>> graph;
62    set<vector<int>> visited;
63    map<int, vector<vector<int>>> nodesInComp;
64    
65    bool overlap(vector<int>& a, vector<int>& b){
66        return a[0] <= b[1] && b[0] <= a[1];
67    }
68    
69    void buildGraph(vector<vector<int>>& intervals){
70        for(vector<int>& interval1 : intervals){
71            for(vector<int>& interval2: intervals){
72                if(overlap(interval1, interval2)){
73                    graph[interval1].push_back(interval2);
74                    graph[interval2].push_back(interval1);
75                }
76            }
77        }
78    };
79    
80    void markComponentDFS(vector<int>& start, int compNumber){
81        stack<vector<int>> stk;
82        
83        stk.push(start);
84        
85        while(!stk.empty()){
86            vector<int> node = stk.top(); stk.pop();
87            if(visited.find(node) == visited.end()){
88                visited.insert(node);
89                
90                nodesInComp[compNumber].push_back(node);
91                
92                for(vector<int>& child : graph[node]){
93                    stk.push(child);
94                }
95            }
96        }
97    };
98    
99    void buildComponents(vector<vector<int>>& intervals){
100        int compNumber = 0;
101        for(vector<int>& interval : intervals){
102            if(visited.find(interval) == visited.end()){
103                markComponentDFS(interval, compNumber);
104                compNumber++;
105            }
106        }
107    };
108    
109    vector<int> mergeNodes(vector<vector<int>> nodes){
110        int minStart = nodes[0][0];
111        int maxEnd = nodes[0][1];
112        
113        for(vector<int>& node : nodes){
114            minStart = min(minStart, node[0]);
115            maxEnd = max(maxEnd, node[1]);
116        }
117        
118        return vector<int>{minStart, maxEnd};
119    };
120    
121    vector<vector<int>> merge(vector<vector<int>>& intervals) {
122        buildGraph(intervals);
123        buildComponents(intervals);
124        
125        vector<vector<int>> merged;
126        for(int comp = 0; comp < nodesInComp.size(); comp++){
127            merged.push_back(mergeNodes(nodesInComp[comp]));
128        }
129        
130        return merged;
131    }
132};

Cost

Complexity

Time
O(build graph) + O(traverse graph) + O(merge) = O(V+E) + O(V+E) +O(V) = O(n^2+n) + O(n^2+n) + O(n) = O(n^2)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n^2)
Auxiliary state plus the answer structure where the problem requires one.