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: 2
💡 Note: Split at index 2: left product = 4×7×8 = 224 (prime factors: 2⁵×7), right product = 15×3×5 = 225 (prime factors: 3²×5²). No common prime factors, so they are coprime.

Constraints

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

Visualization

Tap to expand
Split Array to Make Coprime Products INPUT nums = [2, 3, 3] 2 i=0 3 i=1 3 i=2 Prime Factorization: 2 = {2} 3 = {3} 3 = {3} Find smallest i where: gcd(left_prod, right_prod) == 1 Valid split: 0 <= i <= n-2 So i can be 0 or 1 ALGORITHM STEPS 1 Get Prime Factors Track last index of each prime 2 Check i=0 Left={2}, Right={3,3} 3 Compute GCD gcd(2, 9) = 1 (coprime!) 4 Return Index Found valid split at i=0 i Left Right GCD 0 {2} {3} 1 1 {2,3} {3} 3 OK - Valid split found at i=0 FINAL RESULT Valid Split at Index 0 2 Left 3, 3 Right Product: 2 Product: 9 gcd(2, 9) = 1 Coprime - OK Output: 0 Smallest valid split index found at i = 0 Key Insight: Two products are coprime if they share NO common prime factors. By tracking the prime factors of elements in left and right parts, we can efficiently check if their intersection is empty. Prime factor sets: Left={2} and Right={3} have no overlap, so gcd=1 at index 0. TutorialsPoint - Split the Array to Make Coprime Products | Prime Factorization with Sets Approach
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