Redundant Connection

Medium Graphs Cycle Detection

Redundant Connection is a medium graphs problem solved with the cycle detection pattern. The best approach, optimal (union-find), runs in O(n · α(n)) time and O(n) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (remove each edge and test) up.

Problem

A graph started out as a tree on n nodes labeled 1 to n: connected, with no cycles. Then one extra edge was added between two different nodes that were not already directly joined.

You get the resulting graph as a list edges of length n, where edges[i] = [ai, bi] is an undirected edge between ai and bi.

Return an edge whose removal turns the graph back into a tree on all n nodes. If more than one edge would work, return the one that appears last in edges.

Examples

Example 1

Input
edges = [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]
Output
[1, 4]
Why
The edges 1-2, 2-3, 3-4 and 1-4 form a loop of four nodes. Removing any one of those four leaves a tree, and of the four, [1, 4] appears last in the input. Removing [1, 5] would cut node 5 off, so it is not a choice.

Example 2

Input
edges = [[1, 2], [1, 3], [2, 3]]
Output
[2, 3]
Why
The three edges form a triangle. Any of them could go, and [2, 3] is the last one listed.

Example 3

Input
edges = [[1, 4], [3, 4], [1, 3], [1, 2], [4, 5]]
Output
[1, 3]
Why
The loop is 1-4, 4-3, 3-1. [1, 3] is the last of those three in the input. The edges after it, [1, 2] and [4, 5], are needed to reach nodes 2 and 5.

Constraints

  • n == edges.length
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= ai < bi <= n
  • There are no repeated edges.
  • The graph is connected.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (remove each edge and test)O(n^2)O(n)
Add edges one by one, check with DFSO(n^2)O(n)
Optimal (Union-Find)O(n · α(n))O(n)

1Brute force (remove each edge and test)

TimeO(n^2)Up to n candidates, and each one rebuilds the graph and searches it in O(n).
SpaceO(n)The adjacency list, the seen array and the stack hold O(n) entries for one candidate at a time.

Try the candidates from the last edge to the first. For a candidate, build the graph from the other n - 1 edges and run a search from node 1. Since n - 1 edges on n nodes form a tree exactly when they connect everything, the candidate is valid if the search reaches all n nodes. Going from the back, the first valid candidate is the one that appears last in the input.

  1. For skip from n - 1 down to 0:
  2. Build an adjacency list from every edge except edges[skip].
  3. Search from node 1 with a stack and count the nodes reached.
  4. If the count is n, return edges[skip].
class Solution {
    public int[] findRedundantConnection(int[][] edges) {
        int n = edges.length;
        for (int skip = n - 1; skip >= 0; skip--) {
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
            for (int i = 0; i < n; i++) {
                if (i == skip) continue;
                adj.get(edges[i][0]).add(edges[i][1]);
                adj.get(edges[i][1]).add(edges[i][0]);
            }
            boolean[] seen = new boolean[n + 1];
            Deque<Integer> stack = new ArrayDeque<>();
            stack.push(1);
            seen[1] = true;
            int count = 1;
            while (!stack.isEmpty()) {
                int u = stack.pop();
                for (int v : adj.get(u)) {
                    if (!seen[v]) {
                        seen[v] = true;
                        count++;
                        stack.push(v);
                    }
                }
            }
            if (count == n) return edges[skip];
        }
        return new int[0];
    }
}

2Add edges one by one, check with DFS

TimeO(n^2)Each of the n edges triggers one DFS over a forest of at most n nodes and n - 1 edges.
SpaceO(n)The adjacency list, the seen array and the recursion depth are all O(n).

Build the graph edge by edge, in input order. Before adding an edge (u, v), run a depth-first search from u in the graph built so far. If it already reaches v, then u and v were connected without this edge, so this edge closes the cycle. Every edge of the cycle except this one was added earlier, which makes it the cycle edge that appears last, exactly the one asked for. Otherwise add the edge and continue.

  1. Start with an empty adjacency list for nodes 1 to n.
  2. For each edge (u, v) in order: run a DFS from u with a fresh seen array; if it reaches v, return this edge.
  3. Otherwise add v to u's list and u to v's list.
class Solution {
    public int[] findRedundantConnection(int[][] edges) {
        int n = edges.length;
        List<List<Integer>> adj = new ArrayList<>();
        for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
        for (int[] e : edges) {
            if (connected(adj, e[0], e[1], new boolean[n + 1])) return e;
            adj.get(e[0]).add(e[1]);
            adj.get(e[1]).add(e[0]);
        }
        return new int[0];
    }

    private boolean connected(List<List<Integer>> adj, int u, int target, boolean[] seen) {
        if (u == target) return true;
        seen[u] = true;
        for (int v : adj.get(u)) {
            if (!seen[v] && connected(adj, v, target, seen)) return true;
        }
        return false;
    }
}

3Optimal (Union-Find)

TimeO(n · α(n))Each edge costs two finds and at most one union, each almost constant (α is the inverse Ackermann function, at most 4 in practice).
SpaceO(n)The parent and size arrays hold n + 1 entries each.

Same idea as adding edges one by one, but answer 'are u and v already connected?' with a disjoint-set structure instead of a search. Every node starts in its own set. For each edge, find the roots of its two ends. Different roots: the edge joins two separate pieces, so merge them, hanging the smaller set under the larger. Same root: the ends were already connected, so this edge closes the cycle and is the answer. Path halving in find keeps the trees shallow.

  1. Set parent[i] = i and size[i] = 1 for every node 1 to n.
  2. For each edge (u, v) in order: a = find(u), b = find(v).
  3. If a == b, return this edge.
  4. Otherwise attach the smaller root under the larger one and add the sizes.
  5. find(x) walks up to the root, pointing each node it passes at its grandparent.
class Solution {
    private int[] parent;
    private int[] size;

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

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

Edge cases to test

  • The loop is a triangle: the smallest possible cycle
  • The loop runs through all n nodes: the answer is the edge of the loop that comes last in the input
  • The loop is closed early and many tree edges follow it: the answer is not the last edge of the input
  • A long path whose two ends are joined by the extra edge, which makes a depth-first search as deep as n
  • Several edges could be removed: only the one appearing last among them is correct

Hints

Hint 1

A tree on n nodes has exactly n - 1 edges. With n edges there is exactly one cycle, and removing any edge of that cycle leaves a tree.

Hint 2

Brute force: try removing each edge, starting from the last one, and check whether the other edges form a connected graph.

Hint 3

Add the edges one by one. The first edge whose two ends are already connected is the one that closes the cycle, and it is the cycle edge that appears last.

Hint 4

A disjoint-set (Union-Find) structure answers 'are u and v already connected?' in almost constant time.

FAQ

What is the best time complexity for Redundant Connection?

Optimal (Union-Find) runs in O(n · α(n)) time and O(n) extra space. Each edge costs two finds and at most one union, each almost constant (α is the inverse Ackermann function, at most 4 in practice).

Which pattern does Redundant Connection use?

It is a graphs problem that uses the cycle detection pattern. Other problems with the same pattern: Undirected Graph Cycle, Directed Graph Cycle, Is Graph Bipartite?.

Is there a brute force solution for Redundant Connection?

Yes. Brute force (remove each edge and test) takes O(n^2) time and O(n) space. Try the candidates from the last edge to the first.

Which edge cases should I test for Redundant Connection?

The loop is a triangle: the smallest possible cycle; The loop runs through all n nodes: the answer is the edge of the loop that comes last in the input; The loop is closed early and many tree edges follow it: the answer is not the last edge of the input; A long path whose two ends are joined by the extra edge, which makes a depth-first search as deep as n; Several edges could be removed: only the one appearing last among them is correct.