Minimum Split Into Subarrays With GCD Greater Than One — LeetCode 2436 Python Solution

MediumLeetCode PremiumGreedyArrayMathDynamic ProgrammingNumber Theory
Problem
#2436
Pattern
Greedy
Reading time
2 min

The problem

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.

Example

Input
nums = [12,6,3,14,8]
Output
2
Explanation
We can split the array into the subarrays: [12,6,3] and [14,8].

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times \log m), where n and m are the length of the array and the maximum value in the array, respectively
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One?
LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One is rated Medium on LeetCode.
What is the time complexity of LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One?
The Python solution on this page runs in O(n \times \log m), where n and m are the length of the array and the maximum value in the array, respectively.
What is the space complexity of LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One cover?
LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One is tagged Greedy, Array, Math, Dynamic Programming and Number Theory on LeetCode.
Is LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One a premium problem?
Yes. LeetCode 2436. Minimum Split Into Subarrays With GCD Greater Than One is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview