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
Cookie Factory: Minimum Box Packing12ingredients6ingredients3ingredients14ingredients8ingredientsBox 1Shared ingredients: 3Box 2Shared ingredients: 2๐Ÿ”„ GCD(12, 6) = 6 > 1 โ†’ Add to Box 1๐Ÿ”„ GCD(6, 3) = 3 > 1 โ†’ Add to Box 1โŒ GCD(3, 14) = 1 โ†’ Start Box 2๐Ÿ”„ GCD(14, 8) = 2 > 1 โ†’ Add to Box 2โœ… Result: 2 boxes minimum
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.
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
42.3K Views
Medium-High Frequency
~18 min Avg. Time
1.5K 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