Split the Array to Make Coprime Products - Problem
You are given a 0-indexed integer array nums of length n.
Your task is to find the smallest valid split index where you can divide the array into two parts such that the product of all elements in the left part and the product of all elements in the right part are coprime (their greatest common divisor is 1).
A split at index i (where 0 ≤ i ≤ n-2) divides the array into:
- Left part: elements from index 0 to i (inclusive)
- Right part: elements from index i+1 to n-1 (inclusive)
Example: If nums = [2, 3, 3]:
- Split at
i = 0: Left product = 2, Right product = 3 × 3 = 9. Since gcd(2, 9) = 1, this is valid ✅ - Split at
i = 1: Left product = 2 × 3 = 6, Right product = 3. Since gcd(6, 3) = 3 ≠ 1, this is invalid ❌
Return the smallest index i where a valid split exists, or -1 if no valid split is possible.
Two numbers are coprime if their greatest common divisor (GCD) equals 1.
Input & Output
example_1.py — Basic Valid Split
$
Input:
[2, 3, 3]
›
Output:
0
💡 Note:
Split at index 0: Left product = 2, Right product = 3 × 3 = 9. Since gcd(2, 9) = 1, they are coprime. This is the smallest valid index.
example_2.py — No Valid Split
$
Input:
[4, 7, 8, 15, 3, 5]
›
Output:
-1
💡 Note:
For every possible split, the left and right products share at least one common prime factor, so no valid split exists.
example_3.py — Multiple Options
$
Input:
[4, 7, 15, 8, 3, 5]
›
Output:
0
💡 Note:
Split at index 0: Left = 4 (prime factors: {2}), Right = 7×15×8×3×5 (prime factors: {3,5,7,2}). Wait, they share factor 2, so this is invalid. Need to check all splits carefully.
Constraints
- 2 ≤ nums.length ≤ 104
- 1 ≤ nums[i] ≤ 106
- All array elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Extract the Gems
Break down each number into its prime factor 'gems': 2→{blue gem}, 3→{red gem}, 6→{blue gem, red gem}
2
Split the Collection
Try splitting at each position, collecting gems on the left vs right
3
Check for Color Conflicts
If left and right collections share any gem color, they're not coprime
4
Find Pure Separation
Return the first split where left and right have completely different colored gems
Key Takeaway
🎯 Key Insight: Instead of calculating huge products that might overflow, we only need to track which prime factors exist on each side. Two numbers are coprime exactly when their prime factor sets don't overlap!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code