Check If It Is a Good Array Problem
Description
LeetCode Problem 1250.
Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.
Return True if the array is good otherwise return False.
Example 1:
Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
Example 2:
Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
Example 3:
Input: nums = [3,6]
Output: false
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Greatest Common Divisor (Bezout's Identity)
Trying subsets and multipliers is hopeless, but number theory answers the question directly. Bezout's identity says that integers a1, a2, ..., ak have an integer combination a1·x1 + a2·x2 + ... + ak·xk equal to 1 exactly when gcd(a1, ..., ak) = 1.
- If the chosen subset has gcd
g, every combination of it is a multiple ofg, so it can reach 1 only wheng = 1. - Using more numbers never hurts: the gcd of the whole array divides the gcd of every subset. If some subset has gcd 1, so does the whole array, and the other numbers can simply get multiplier 0.
So the array is good exactly when the gcd of all its numbers is 1. We fold the gcd over the array, starting from gcd(0, x) = x, and stop early as soon as it reaches 1, since it can never grow again. For [12, 5, 7, 23] the gcd drops to 1 after 12 and 5. For [3, 6] it stays 3, so the answer is false.
Complexity: O(n log M) time, where M is the largest number (each gcd takes O(log M) steps), and O(1) extra space.
from math import gcd
class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
# Bezout: some integer combination of the numbers equals 1 exactly when their gcd is 1.
g = 0
for x in nums:
g = gcd(g, x)
if g == 1:
return True
return False