Leetcode #685: Redundant Connection II
In this guide, we solve Leetcode #685 Redundant Connection II in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Union Find, Graph
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Python Solution
class Solution:
def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
n = len(edges)
ind = [0] * n
for _, v in edges:
ind[v - 1] += 1
dup = [i for i, (_, v) in enumerate(edges) if ind[v - 1] == 2]
p = list(range(n))
if dup:
for i, (u, v) in enumerate(edges):
if i == dup[1]:
continue
pu, pv = find(u - 1), find(v - 1)
if pu == pv:
return edges[dup[0]]
p[pu] = pv
return edges[dup[1]]
for i, (u, v) in enumerate(edges):
pu, pv = find(u - 1), find(v - 1)
if pu == pv:
return edges[i]
p[pu] = pv
Complexity
The time complexity is , and the space complexity is , where is the number of edges. The space complexity is , where is the number of edges.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.