Skip to content

Commit 9b41521

Browse files
authored
Update largest-component-size-by-common-factor.py
1 parent 4736050 commit 9b41521

File tree

1 file changed

+56
-3
lines changed

1 file changed

+56
-3
lines changed

Python/largest-component-size-by-common-factor.py

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def largestComponentSize(self, A):
2929
:type A: List[int]
3030
:rtype: int
3131
"""
32-
def primeFactors(i): # prime factor decomposition
32+
def prime_factors(i): # prime factor decomposition
3333
result = []
3434
d = 2
3535
if i%d == 0:
@@ -43,14 +43,67 @@ def primeFactors(i): # prime factor decomposition
4343
i //= d
4444
result.append(d)
4545
d += 2
46-
if i > 2:
46+
if i != 1:
4747
result.append(i)
4848
return result
4949

5050
union_find = UnionFind(len(A))
5151
nodesWithCommonFactor = collections.defaultdict(int)
5252
for i in xrange(len(A)):
53-
for factor in primeFactors(A[i]):
53+
for factor in prime_factors(A[i]):
54+
if factor not in nodesWithCommonFactor:
55+
nodesWithCommonFactor[factor] = i
56+
union_find.union_set(nodesWithCommonFactor[factor], i)
57+
return max(union_find.size)
58+
59+
60+
# Time: O(f * n), f is the max number of unique prime factors
61+
# Space: O(p + n), p is the total number of unique primes
62+
import collections
63+
64+
65+
class UnionFind(object):
66+
def __init__(self, n):
67+
self.set = range(n)
68+
self.size = [1]*n
69+
70+
def find_set(self, x):
71+
if self.set[x] != x:
72+
self.set[x] = self.find_set(self.set[x]) # path compression.
73+
return self.set[x]
74+
75+
def union_set(self, x, y):
76+
x_root, y_root = map(self.find_set, (x, y))
77+
if x_root == y_root:
78+
return False
79+
self.set[min(x_root, y_root)] = max(x_root, y_root)
80+
self.size[max(x_root, y_root)] += self.size[min(x_root, y_root)]
81+
return True
82+
83+
84+
class Solution2(object):
85+
def largestComponentSize(self, A):
86+
"""
87+
:type A: List[int]
88+
:rtype: int
89+
"""
90+
def prime_factors(x): # prime factor decomposition
91+
result = []
92+
p = 2
93+
while p*p <= x:
94+
if x%p == 0:
95+
while x%p == 0:
96+
x //= p
97+
result.append(p)
98+
p += 1
99+
if x != 1:
100+
result.append(x)
101+
return result
102+
103+
union_find = UnionFind(len(A))
104+
nodesWithCommonFactor = collections.defaultdict(int)
105+
for i in xrange(len(A)):
106+
for factor in prime_factors(A[i]):
54107
if factor not in nodesWithCommonFactor:
55108
nodesWithCommonFactor[factor] = i
56109
union_find.union_set(nodesWithCommonFactor[factor], i)

0 commit comments

Comments
 (0)