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 in a Valid Split INPUT nums array: 4 idx 0 6 idx 1 15 idx 2 35 idx 3 Valid Split Rule: GCD(first, last) > 1 for each subarray GCD Examples: GCD(4,6) = 2 [OK] GCD(15,35) = 5 [OK] nums = [4, 6, 15, 35] ALGORITHM STEPS 1 Start at index 0 Try to extend subarray 2 Check GCD greedy Extend while GCD > 1 3 Split when needed GCD(4,15)=1, split here 4 Count subarrays Return total count Greedy Trace: [4,6] GCD(4,6)=2 [OK] [4,6,15] GCD(4,15)=1 SPLIT [15,35] GCD(15,35)=5 [OK] FINAL RESULT Valid Split Found: Subarray 1 [4, 6] GCD=2 Subarray 2 [15, 35] GCD=5 Validation: GCD(4,6) = 2 > 1 [OK] GCD(15,35) = 5 > 1 [OK] OUTPUT 2 Minimum splits achieved! All elements covered Key Insight: Greedy approach: Extend each subarray as far as possible while maintaining GCD(first, last) > 1. When GCD becomes 1, start a new subarray. This minimizes total subarrays since we maximize each one. TutorialsPoint - Minimum Subarrays in a Valid Split | Greedy Approach
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