Minimum Split Into Subarrays With GCD Greater Than One - Problem

You are given an array nums consisting of positive integers. Split the array into one or more disjoint subarrays such that:

  • Each element of the array belongs to exactly one subarray
  • The GCD of the elements of each subarray is strictly greater than 1

Return the minimum number of subarrays that can be obtained after the split.

Note that:

  • The GCD of a subarray is the largest positive integer that evenly divides all the elements of the subarray.
  • A subarray is a contiguous part of the array.

Input & Output

Example 1 — Basic Split
$ Input: nums = [12,6,3,14,8]
Output: 2
💡 Note: Split into [12,6,3] with GCD=3 and [14,8] with GCD=2. Both have GCD > 1, so minimum splits = 2.
Example 2 — Single Element
$ Input: nums = [4]
Output: 1
💡 Note: Single element [4] has GCD=4 > 1, so we need only 1 subarray.
Example 3 — Each Element Separate
$ Input: nums = [6,10,15]
Output: 3
💡 Note: GCD(6,10)=2, but adding 15 makes GCD(6,10,15)=1. So split as [6],[10],[15] with 3 subarrays.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Split Into Subarrays With GCD > 1 INPUT nums = [12, 6, 3, 14, 8] 12 i=0 6 i=1 3 i=2 14 i=3 8 i=4 Goal: Split into minimum subarrays where each has GCD > 1 GCD Examples: GCD(12,6) = 6 GCD(6,3) = 3 GCD(3,14) = 1 (BAD!) GCD(14,8) = 2 Constraint: GCD of each subarray > 1 GREEDY ALGORITHM 1 Initialize currentGCD = nums[0] = 12 count = 1 2 Extend Subarray GCD(12,6)=6 > 1, extend GCD(6,3)=3 > 1, extend 3 Split When Needed GCD(3,14)=1, must split! Start new: GCD=14, count=2 4 Continue GCD(14,8)=2 > 1, extend End of array reached Iteration Trace: i=1: GCD=6, cnt=1 i=2: GCD=3, cnt=1 i=3: SPLIT! i=4: GCD=2, cnt=2 FINAL RESULT Optimal Split: Subarray 1 12 6 3 GCD=3 Subarray 2 14 8 GCD=2 Output 2 Minimum splits = 2 OK - Optimal! Key Insight: Greedy approach works because extending a subarray can only decrease or maintain the GCD (never increase). When GCD becomes 1, we must split. Starting a new subarray resets GCD to the current element, which is always > 1 (given positive integers). Time: O(n log M), Space: O(1). TutorialsPoint - Minimum Split Into Subarrays With GCD Greater Than One | Greedy Approach
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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