-
Notifications
You must be signed in to change notification settings - Fork 0
/
lc_0684_redundant_connection.py
57 lines (45 loc) · 1.69 KB
/
lc_0684_redundant_connection.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# https://leetcode.com/problems/redundant-connection/solutions/4598163/strip-out-the-leaves-and-the-cycle-is-revealed
"""Strip out the leaves and the cycle is revealed.
We apply topological sort to remove everything except the cycle.
Time complexity: O(n) (we perform constant operations per vertex), assuming accessing the dictionary is constant.
Space complexity: O(n) (we store constant additional info per node)
"""
import unittest
from collections import defaultdict
from typing import List
class Solution:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
# Process the edges into a vertex dictionary.
v = defaultdict(set)
for a, b in edges:
v[a].add(b)
v[b].add(a)
# Strip out the tree part, starting from the leaves.
leaves = {x for x, e in v.items() if len(e) == 1}
while leaves:
x = leaves.pop()
y = v[x].pop()
assert not v[x]
del v[x]
v[y].remove(x)
if len(v[y]) == 1:
leaves.add(y)
# Only the cycle is left now.
assert all(len(e) == 2 for e in v.values())
for a, b in reversed(edges):
if a in v and b in v[a]:
return [a, b]
class TestSolution(unittest.TestCase):
def setUp(self):
self.solution = Solution().findRedundantConnection
def test_findRedundantConnection(self):
self.assertEqual(
self.solution([[1, 2], [1, 3], [2, 3]]),
[2, 3],
)
self.assertEqual(
self.solution([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]),
[1, 4],
)
if __name__ == "__main__":
unittest.main()