Skip to content

Commit 852cbe7

Browse files
authored
Create split-the-array-to-make-coprime-products.py
1 parent cbc4e63 commit 852cbe7

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(n * sqrt(r)), r = max(nums)
2+
# Space: O(sqrt(r))
3+
4+
import collections
5+
6+
7+
# number theory
8+
class Solution(object):
9+
def findValidSplit(self, nums):
10+
"""
11+
:type nums: List[int]
12+
:rtype: int
13+
"""
14+
def factorize(x):
15+
result = []
16+
d = 2
17+
while d*d <= x:
18+
e = 0
19+
while x%d == 0:
20+
x //= d
21+
e += 1
22+
if e:
23+
result.append([d, e])
24+
d += 1 if d == 2 else 2
25+
if x > 1:
26+
result.append([x, 1])
27+
return result
28+
29+
right = collections.Counter()
30+
for x in reversed(nums):
31+
for p, c in factorize(x):
32+
right[p] += c
33+
left = collections.Counter()
34+
cnt = 0
35+
for i in xrange(len(nums)-1):
36+
for p, c in factorize(nums[i]):
37+
if not left[p]:
38+
cnt += 1
39+
left[p] += c
40+
right[p] -= c
41+
if not right[p]:
42+
cnt -= 1
43+
if not cnt:
44+
return i
45+
return -1

0 commit comments

Comments
 (0)