Minimum Subarrays in a Valid Split Problem
#2464
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2464.
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
numsbelongs 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.
Example 1:
Input: nums = [2,6,3,4,3]
Output: 2
Explanation: We can create a valid split in the following way: [2,6] | [3,4,3].
- The starting element of the 1^st subarray is 2 and the ending is 6. Their greatest common divisor is 2, which is greater than 1.
- The starting element of the 2^nd subarray is 3 and the ending is 3. Their greatest common divisor is 3, which is greater than 1.
It can be proved that 2 is the minimum number of subarrays that we can obtain in a valid split.
Example 2:
Input: nums = [3,5]
Output: 2
Explanation: We can create a valid split in the following way: [3] | [5].
- The starting element of the 1^st subarray is 3 and the ending is 3. Their greatest common divisor is 3, which is greater than 1.
- The starting element of the 2^nd subarray is 5 and the ending is 5. Their greatest common divisor is 5, which is greater than 1.
It can be proved that 2 is the minimum number of subarrays that we can obtain in a valid split.
Example 3:
Input: nums = [1,2,1]
Output: -1
Explanation: It is impossible to create valid split.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 10^5
Solution
Approach: DP
Let dfs(i) be the minimum number of subarrays needed for nums[i..]. Try every end j >= i of the first subarray: it is valid when gcd(nums[i], nums[j]) > 1, and then the cost is 1 + dfs(j + 1). The answer is the minimum over all valid j, or "impossible" when none exists. With dfs(n) = 0, return -1 if dfs(0) is impossible.
Complexity: O(n2) gcd calls and O(n) space, where n is the length of the array.
from functools import lru_cache
from math import gcd, inf
class Solution:
def validSubarraySplit(self, nums: List[int]) -> int:
@lru_cache(None)
def dfs(i):
if i >= n:
return 0
ans = inf
for j in range(i, n):
if gcd(nums[i], nums[j]) > 1:
ans = min(ans, 1 + dfs(j + 1))
return ans
n = len(nums)
ans = dfs(0)
dfs.cache_clear()
return ans if ans < inf else -1