← Home

684. Redundant Connection

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
union-findC++Markdown
684

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 684. Redundant Connection, the solution in this repository is mainly a union-find solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. 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: union-find.

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

  • Sol Approach #1: DFS
  • time complexity: O(N^2), space complexity: O(N)

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 important function names to track are dfs, findRedundantConnection, unite.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • 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. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

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^2), space complexity: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Sol Approach #1: DFS
02//Runtime: 28 ms, faster than 11.45% of C++ online submissions for Redundant Connection.
03//Memory Usage: 14.6 MB, less than 5.88% of C++ online submissions for Redundant Connection.
04//time complexity: O(N^2), space complexity: O(N)
05class Solution {
06public:
07    set<int> seen;
08    int MAX_EDGE_VAL = 1000;
09    
10    bool dfs(vector<vector<int>>& graph, int source, int target){
11        //check if source and target can be connected in graph
12        if(seen.find(source) == seen.end()){
13            seen.insert(source);
14            if(source == target) return true;
15            for(int nei : graph[source]){
16                //if one success, return true
17                if(dfs(graph, nei, target)) return true;
18            }
19        }
20        //if all fail, return false
21        return false;
22    }
23    
24    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
25        vector<vector<int>> graph(MAX_EDGE_VAL+1);
26        
27        //check while building graph
28        for(vector<int>& edge : edges){
29            seen.clear();
30            //if edge[0] and edge[1] can be connected through other edges
31            if(!graph[edge[0]].empty() &&
32              !graph[edge[1]].empty() && 
33               dfs(graph, edge[0], edge[1])) {
34                //then current edge is redundant
35                return edge;
36            }
37            //insert the non-redundant edge into graph
38            graph[edge[0]].push_back(edge[1]);
39            graph[edge[1]].push_back(edge[0]);
40        }
41        
42        return vector<int>();
43    }
44};
45
46//Approach #2: Union-Find
47//Runtime: 8 ms, faster than 79.50% of C++ online submissions for Redundant Connection.
48//Memory Usage: 10.3 MB, less than 47.06% of C++ online submissions for Redundant Connection.
49class DSU{
50private:
51    vector<int> parent;
52    vector<int> rank;
53public:
54    DSU(int size){
55        parent = vector<int>(size);
56        iota(parent.begin(), parent.end(), 0);
57        rank = vector<int>(size);
58    };
59    
60    int find(int x){
61        if(parent[x] != x){
62            parent[x] = find(parent[x]);
63        }
64        return parent[x];
65    };
66    
67    bool unite(int x, int y){
68        int xp = find(x), yp = find(y);
69        if(xp == yp){
70            //x and y is already connected
71            return false;
72        }else if(rank[xp] < rank[yp]){
73            //union-by-rank
74            parent[xp] = yp;
75        }else if(rank[xp] > rank[yp]){
76            parent[yp] = xp;
77        }else{
78            parent[yp] = xp;
79            rank[xp]++;
80        }
81        //now x and y is connected
82        return true;
83    };
84};
85
86class Solution {
87public:
88    int MAX_EDGE_VAL = 1000;
89    
90    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
91        DSU dsu = DSU(MAX_EDGE_VAL+1);
92        for(vector<int>& edge : edges){
93            if(!dsu.unite(edge[0], edge[1])){
94                return edge;
95            }
96        }
97        return vector<int>();
98    }
99};
100
101//WA
102class Solution {
103public:
104    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
105        // cout << edges.size() << endl;
106        for(int i = edges.size()-1; i >= 0; i--){
107            int x = edges[i][0], y = edges[i][1];
108            bool first = false, second = false;
109            for(int j = 0; j < i; j++){
110                if(find(edges[j].begin(), edges[j].end(), x) != edges[j].end()){
111                    first = true;
112                }else if(find(edges[j].begin(), edges[j].end(), y) != edges[j].end()){
113                    second = true;
114                }
115                if(first && second) return edges[i];
116            }
117            
118        }
119        return vector<int>();
120    }
121};

Cost

Complexity

Time
O(N^2), space complexity: O(N)
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.