Problem Description
Given an array of positive integers, split the array into one or more contiguous subarrays such that every subarray has a GCD (greatest common divisor) strictly greater than 1. Return the minimum number of subarrays needed to achieve this.
Key Insights
- A single element always has a GCD equal to itself (and since each nums[i] ≥ 2, a single-element subarray is valid).
- The challenge is to group contiguous elements such that the GCD of the group exceeds 1.
- Use dynamic programming where dp[i] represents the minimum splits for the prefix ending at index i-1.
- While iterating backwards from a given index, maintain the running GCD; if it remains above 1, update dp for the current segment.
- Once the running GCD falls to 1, further extension will never improve it (since adding more numbers cannot restore the GCD to above 1), so break early from the inner loop for efficiency.
Space and Time Complexity
Time Complexity: O(n² * log(max(nums))) — The outer loop runs for n elements and the inner loop can run up to n iterations with GCD computation taking O(log(max(nums))). Space Complexity: O(n) — Only an extra dp array of size n+1 is used.
Solution
The solution uses a dynamic programming approach:
- Create a dp array where dp[i] represents the minimum number of subarrays needed for the first i elements.
- Initialize dp[0] = 0.
- For every index i in the array, iterate backwards updating the current GCD for the subarray ending at i.
- If at a certain point the current GCD is more than 1, update dp[i+1] = min(dp[i+1], dp[j] + 1) where j is the start index of the subarray.
- Stop the inner loop early if the current GCD becomes 1.
- The answer is dp[n] where n is the length of the array.
Data Structures and Algorithms Used:
- Dynamic Programming: to record and update the minimum splits needed.
- Iterative GCD computation: using the Euclidean algorithm for efficiently computing the GCD.
- Greedy early exit in the inner loop when further extension is non-beneficial.