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 = 0
is valid because2
and9
are coprime, while a split at the indexi = 1
is not valid because6
and3
are not coprime. A split at the indexi = 2
is 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.length
1 <= n <= 10^4
1 <= nums[i] <= 10^6
Problem Analysis:
Assume we find the index i, such that the two parts(0-i, i+1 — n) don’t have common factors.
So we can first count all factors, and iterate to find index i (make no factor exists in two parts).
Solution
class Solution {
public:
int findValidSplit(vector<int>& nums) {
unordered_map<int, int> left, right;
for (const auto& item : nums) {
for (const auto& value : factorial(item))
++right[value];
}
for (int i = 0; i < nums.size() - 1; ++i) {
for (const auto& item : factorial(nums[i])) {
if (--right[item] == 0) left.erase(item);
else ++left[item];
}
if (left.empty()) return i;
}
return -1;
}
vector<int> factorial(int value) {
int max_item{(int)sqrt(value)};
vector<int> res;
for (int i = 2; i <= max_item; i += 1 + (i % 2)) {
if (value % i == 0) {
res.push_back(i);
while (value % i == 0) value /= i;
}
}
if (value > 1) res.push_back(value);
return res;
}
};
Time complexity is O(n)
Space complexity is O(n)