Skip to content

Commit 07be4fe

Browse files
authored
Create largest-component-size-by-common-factor.py
1 parent d98a784 commit 07be4fe

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Time: O(f * n), f is the total number of unique prime factors
2+
# Soace: O(f * n)
3+
4+
import collections
5+
6+
7+
class UnionFind(object):
8+
def __init__(self, n):
9+
self.set = range(n)
10+
self.size = [1]*n
11+
12+
def find_set(self, x):
13+
if self.set[x] != x:
14+
self.set[x] = self.find_set(self.set[x]) # path compression.
15+
return self.set[x]
16+
17+
def union_set(self, x, y):
18+
x_root, y_root = map(self.find_set, (x, y))
19+
if x_root == y_root:
20+
return False
21+
self.set[min(x_root, y_root)] = max(x_root, y_root)
22+
self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]
23+
return True
24+
25+
26+
class Solution(object):
27+
def largestComponentSize(self, A):
28+
"""
29+
:type A: List[int]
30+
:rtype: int
31+
"""
32+
def primeFactors(i): # Prime factor decomposition
33+
result = []
34+
d = 2
35+
if i%d == 0:
36+
while i%d == 0:
37+
i /= d
38+
result.append(d)
39+
d = 3
40+
while d*d <= i:
41+
if i%d == 0:
42+
while i%d == 0:
43+
i /= d
44+
result.append(d)
45+
d += 2
46+
if i > 2:
47+
result.append(i)
48+
return result
49+
50+
nodesWithCommonFactor = collections.defaultdict(list)
51+
for i in xrange(len(A)):
52+
for factor in primeFactors(A[i]):
53+
nodesWithCommonFactor[factor].append(i)
54+
55+
union_find = UnionFind(len(A))
56+
for _, nodes in nodesWithCommonFactor.iteritems():
57+
for i in xrange(1, len(nodes)):
58+
union_find.union_set(nodes[0], nodes[i])
59+
return max(union_find.size)

0 commit comments

Comments
 (0)