Minimum Subarrays in a Valid Split - Problem

You are given an integer array nums. Splitting of an integer array nums into subarrays is valid if:

  • The greatest common divisor of the first and last elements of each subarray is greater than 1, and
  • Each element of nums belongs to exactly one subarray.

Return the minimum number of subarrays in a valid subarray splitting of nums. If a valid subarray splitting is not possible, return -1.

Note that:

  • The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
  • A subarray is a contiguous non-empty part of an array.

Input & Output

Example 1 — Basic Valid Split
$ Input: nums = [4,6,15,35]
Output: 2
💡 Note: Split into [4,6] and [15,35]. GCD(4,6)=2>1 and GCD(15,35)=5>1, both valid.
Example 2 — Single Element Subarrays
$ Input: nums = [6,2,3,4]
Output: 4
💡 Note: Each element forms its own subarray: [6], [2], [3], [4]. GCD of single element with itself is the element itself, all > 1.
Example 3 — Impossible Split
$ Input: nums = [1,2,3,4,5]
Output: -1
💡 Note: First element is 1. Since GCD(1,x)=1 for any x, no valid subarray starting with 1 can have GCD>1.

Constraints

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

Visualization

Tap to expand
Minimum Subarrays with Valid GCD Split461535Subarray 1Subarray 2GCD(4,6) = 2 > 1 ✓GCD(15,35) = 5 > 1 ✓Valid Split Requirements• GCD(first, last) > 1 for each subarrayMinimum subarrays needed: 2
Understanding the Visualization
1
Input Array
Given array [4,6,15,35] to split into valid subarrays
2
Check GCD
Each subarray must have GCD(first,last) > 1
3
Minimum Split
Find minimum number of subarrays needed
Key Takeaway
🎯 Key Insight: If first element is 1, splitting is impossible since GCD(1,x)=1 always
Asked in
Google 35 Microsoft 28 Amazon 22
28.5K Views
Medium Frequency
~25 min Avg. Time
847 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