Algo-Sim › Advanced Graphs

Redundant Connection

Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input

A tree got one extra edge. Find the edge whose removal leaves a tree (the last such edge in the input) with union-find.

Problem

A tree with nodes 1..n had one extra edge added, so the n edges now contain exactly one cycle. Return an edge you can remove to get a tree back; if several work, return the one that appears last in the input.

Constraints

Edge cases to test

Follow-up questions

What if the graph is directed?
A node may also get two parents; check that case first, then cycles (LC 685).
Why union-find over DFS?
Union-find finds the first edge that closes a cycle in one pass: O(E α(V)), while DFS per edge is O(E²).

Solution

Java

public int[] findRedundantConnection(int[][] edges) {
    int[] parent = new int[edges.length + 1];
    for (int i = 0; i < parent.length; i++) parent[i] = i;
    for (int[] e : edges) {
        int a = find(parent, e[0]), b = find(parent, e[1]);
        if (a == b) return e;
        parent[a] = b;
    }
    return new int[0];
}

private int find(int[] parent, int x) {
    while (parent[x] != x) {
        parent[x] = parent[parent[x]];
        x = parent[x];
    }
    return x;
}

Python

def find_redundant_connection(edges):
    parent = list(range(len(edges) + 1))
    for u, v in edges:
        a, b = find(parent, u), find(parent, v)
        if a == b:
            return [u, v]
        parent[a] = b
    return []


def find(parent, x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> findRedundantConnection(vector<vector<int>> &edges) {
        vector<int> parent = vector<int>(int(edges.size()) + 1);
        for (int i = 0; i < int(parent.size()); i++)
            parent[i] = i;
        for (vector<int> &e : edges) {
            int a = find(parent, e[0]), b = find(parent, e[1]);
            if (a == b)
                return e;
            parent[a] = b;
        }
        return vector<int>(0);
    }

    int find(vector<int> &parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
};

More Advanced Graphs problems