Approach

This is a typical union find method, we can union and get parent with amortized O(1) complexity, and when we find the two nodes are already having the same parent, return the answer (this form a loop).

Code

class Solution {
public:
    struct UnionFind {
        UnionFind(int n) {
            parent.assign(n, 0);
            for(int i = 0 ; i < n ; ++i) parent[i] = i;
            sz.assign(n, 1);
        }
        int GetParent(int a) {
            if(parent[a] != a) parent[a] = GetParent(parent[a]);
            return parent[a];
        }
        bool Union(int a, int b) {
            a = GetParent(a);
            b = GetParent(b);
            if(a == b) return false;
            if(sz[a] < sz[b]) swap(a, b);
            sz[a] += sz[b];
            parent[b] = a;
            return true;
        }
        vector<int> parent;
        vector<int> sz;
    };

    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        UnionFind uf(edges.size() + 1);
        for(const auto& e: edges) {
            if(!uf.Union(e[0],e[1])) return {e[0], e[1]};
        }
        return {};
    }
};