Split the Array to Make Coprime Products - Problem

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 index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == 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.

Input & Output

Example 1 — Basic Valid Split
$ Input: nums = [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.
Example 2 — No Valid Split
$ Input: nums = [2, 6, 3, 4]
Output: -1
💡 Note: No split position creates coprime products. All splits share common factors between left and right products.
Example 3 — Later Valid Split
$ Input: nums = [4, 7, 8, 15, 3, 5]
Output: 3
💡 Note: Split at index 3: left product has factors {2,7}, right product has factors {3,5}. No common prime factors.

Constraints

  • 2 ≤ nums.length ≤ 104
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Split Array to Make Coprime Products233Index 0Index 1Index 2Split here (i=0)Left Product: 2Right Product: 3×3 = 9GCD(2, 9) = 1Coprime ✓ → Return index 0
Understanding the Visualization
1
Input Array
[2, 3, 3] - need to find valid split position
2
Try Split at i=0
Left: [2] (product=2), Right: [3,3] (product=9)
3
Check Coprimality
GCD(2, 9) = 1, so they are coprime → valid split
Key Takeaway
🎯 Key Insight: Two numbers are coprime if they share no common prime factors - track factors instead of computing large products
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen