Split the Array to Make Coprime Products Problem
Description
LeetCode Problem 2584.
You are given a 0-indexed integer array nums of length n.
A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime.
- For example, if
nums = [2, 3, 3], then a split at the indexi = 0is valid because2and9are coprime, while a split at the indexi = 1is not valid because6and3are not coprime. A split at the indexi = 2is not valid becausei == n - 1.
Return the smallest index i at which the array can be split validly or -1 if there is no such split.
Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2.
Example 1:
Input: nums = [4,7,8,15,3,5]
Output: 2
Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
The only valid split is at index 2.
Example 2:
Input: nums = [4,7,15,8,3,5]
Output: -1
Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.
There is no valid split.
Constraints:
n == nums.length1 <= n <= 10^41 <= nums[i] <= 10^6
Solution
Approach: Prime Factors + Intervals
The products overflow, but two products are coprime exactly when the two sides share no prime factor. So every prime must appear only on one side of the cut: its first and last occurrences have to be on the same side.
Factorize every number by trial division. For each prime, remember the index of its first occurrence, and whenever it appears again, extend the reach last[first] of that first index to the current index. Now every index i has a right end last[i] of the stretch that must stay together with it.
Scan from left to right while keeping mx, the furthest right end seen so far (starting from last[0]). If mx < i, no prime crosses the boundary between i - 1 and i, so mx (which equals i - 1) is the answer. If the scan ends without that, return -1.
The time complexity is O(n sqrt(M)) and the space complexity is O(n), where M is the maximum value.
class Solution:
def findValidSplit(self, nums: List[int]) -> int:
first = {}
n = len(nums)
last = list(range(n))
for i, x in enumerate(nums):
j = 2
while j <= x // j:
if x % j == 0:
if j in first:
last[first[j]] = i
else:
first[j] = i
while x % j == 0:
x //= j
j += 1
if x > 1:
if x in first:
last[first[x]] = i
else:
first[x] = i
mx = last[0]
for i, x in enumerate(last):
if mx < i:
return mx
mx = max(mx, x)
return -1