Minimum Split Into Subarrays With GCD Greater Than One Problem
#2436
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 2436.
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, and
- 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.
Example 1:
Input: nums = [12,6,3,14,8]
Output: 2
Explanation: We can split the array into the subarrays: [12,6,3] and [14,8].
- The GCD of 12, 6 and 3 is 3, which is strictly greater than 1.
- The GCD of 14 and 8 is 2, which is strictly greater than 1.
It can be shown that splitting the array into one subarray will make the GCD = 1.
Example 2:
Input: nums = [4,12,6,14]
Output: 1
Explanation: We can split the array into only one subarray, which is the whole array.
Constraints:
1 <= nums.length <= 20002 <= nums[i] <= 10^9
Solution
Approach: Greedy + Mathematics
Extending a subarray can only lower its gcd, so cut as late as possible: keep the gcd g of the current subarray, and when adding x would make it 1, start a new subarray at x instead (g = x, answer plus one). Start with g = 0 and one subarray.
Complexity: The time complexity is O(n log m) and the space complexity is O(1), where n is the length of the array and m its maximum value.
from math import gcd
class Solution:
def minimumSplits(self, nums: List[int]) -> int:
ans, g = 1, 0
for x in nums:
g = gcd(g, x)
if g == 1:
ans += 1
g = x
return ans