Minimum Split Into Subarrays With GCD Greater Than One - Problem
You are given an array nums consisting of positive integers. Your task is to split the array into the minimum number of contiguous subarrays such that:
- Each element belongs to exactly one subarray
- The GCD (Greatest Common Divisor) of each subarray is strictly greater than 1
The GCD of a subarray is the largest positive integer that evenly divides all elements in that subarray. For example, GCD of [6, 9, 12] is 3.
Goal: Return the minimum number of subarrays needed to satisfy the conditions.
Example: For [12, 6, 3, 14, 8], we could split into [12, 6, 3] (GCD=3) and [14, 8] (GCD=2), giving us 2 subarrays.
Input & Output
example_1.py โ Basic Case
$
Input:
[12, 6, 3, 14, 8]
โบ
Output:
2
๐ก Note:
Split into [12,6,3] with GCD=3 and [14,8] with GCD=2. Both subarrays have GCD > 1, so minimum splits = 2.
example_2.py โ All Even Numbers
$
Input:
[4, 6, 8, 2]
โบ
Output:
1
๐ก Note:
All numbers are even, so GCD of entire array is 2 > 1. Only need 1 subarray containing all elements.
example_3.py โ Prime Numbers
$
Input:
[2, 3, 5, 7]
โบ
Output:
4
๐ก Note:
Each prime number must be in its own subarray since GCD of any two different primes is 1. Need 4 subarrays.
Constraints
- 1 โค nums.length โค 105
- 2 โค nums[i] โค 106
- All array elements are positive integers โฅ 2
Visualization
Tap to expand
Understanding the Visualization
1
Start First Box
Place first cookie (12 ingredients) in box, shared ingredients = 12
2
Add Compatible Cookie
Cookie with 6 ingredients shares 6 ingredients with first cookie, add to box
3
Continue Extension
Cookie with 3 ingredients shares 3 ingredients with current box contents
4
Incompatible Cookie
Cookie with 14 ingredients shares only 1 ingredient (GCD=1), start new box
5
New Box Success
Last cookie (8 ingredients) shares 2 ingredients with cookie 14, add to second box
Key Takeaway
๐ฏ Key Insight: Greedy algorithm works because extending a valid subarray (keeping cookies in same box) is always optimal - we never benefit from starting a new box early when we could extend the current one.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code