|
| 1 | +--- |
| 2 | +title: Leetcode 684. Redundant Connection |
| 3 | +description: Explanation for Leetcode 684 - Redundant Connection, and its solution in Python. |
| 4 | +date: 2025-04-24 |
| 5 | +categories: [Leetcode, Graphs, Medium] |
| 6 | +tags: [Leetcode, Python, Study, Graphs, Medium] |
| 7 | +math: true |
| 8 | +--- |
| 9 | + |
| 10 | +## Problem |
| 11 | +[Leetcode 684 - Redundant Connection](https://leetcode.com/problems/redundant-connection/description/) |
| 12 | + |
| 13 | +Example: |
| 14 | +``` |
| 15 | +Input: edges = [[1,2],[1,3],[2,3]] |
| 16 | +Output: [2,3] |
| 17 | +
|
| 18 | +Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]] |
| 19 | +Output: [1,4] |
| 20 | +``` |
| 21 | + |
| 22 | +## Approach |
| 23 | + |
| 24 | +For a graph to have a cycle, every node must have 2 or more neighbors, thus we can use tropological sort to get all the neighbor counts(indegree counts) then if indegree == 1, we can disconnect them first. Once we're all done with the process of disconnecting the 1 neighbor edge, we can loop through the edges. |
| 25 | + |
| 26 | +If the indgree count is == 2, and the adjacent indegree count exists, then we can return that edge. |
| 27 | + |
| 28 | +Here is the Python code for the solution: |
| 29 | +```python |
| 30 | +class Solution: |
| 31 | + def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: |
| 32 | + n = len(edges) |
| 33 | + indegree = [0] * (n+1) |
| 34 | + adj = [[] for _ in range(n+1)] |
| 35 | + |
| 36 | + for u, v in edges: |
| 37 | + adj[u].append(v) |
| 38 | + adj[v].append(u) |
| 39 | + indegree[u] += 1 |
| 40 | + indegree[v] += 1 |
| 41 | + |
| 42 | + q = deque() |
| 43 | + for i in range(1, n+1): |
| 44 | + if indegree[i] == 1: |
| 45 | + q.append(i) |
| 46 | + |
| 47 | + while q: |
| 48 | + node = q.popleft() |
| 49 | + |
| 50 | + indegree[node] -= 1 |
| 51 | + for i in adj[node]: |
| 52 | + indegree[i] -= 1 |
| 53 | + if indegree[i] == 1: |
| 54 | + q.append(i) |
| 55 | + |
| 56 | + for u, v in reversed(edges): |
| 57 | + if indegree[u] == 2 and indegree[v]: |
| 58 | + return [u, v] |
| 59 | + |
| 60 | + return [] |
| 61 | +``` |
| 62 | +## Time Complexity and Space Complexity |
| 63 | + |
| 64 | +Time Complexity: $O(V + E)$ |
| 65 | + |
| 66 | +Space Complexity: $O(V + E)$ |
0 commit comments