Check If It Is a Good Array

hard math gcd number theory

Problem

Given an array nums of positive integers, you can pick any subset of it and multiply each chosen number by any integer (positive, negative, or zero), then sum the products. The array is good if some such combination sums to exactly 1. Return whether nums is good.

By Bézout's identity, integer multipliers producing a sum of 1 exist if and only if the greatest common divisor (GCD) of all the numbers equals 1.

Inputnums = [12, 5, 7, 23]
Outputtrue
gcd(12, 5, 7, 23) = 1, e.g. 5·3 + 7·(-2) + 12·0 + 23·0 = 1. So the array is good.

from math import gcd
from functools import reduce

def is_good_array(nums):
    g = reduce(gcd, nums)
    return g == 1
function gcd(a, b) {
  while (b) { [a, b] = [b, a % b]; }
  return a;
}
function isGoodArray(nums) {
  let g = nums[0];
  for (let i = 1; i < nums.length; i++) g = gcd(g, nums[i]);
  return g === 1;
}
class Solution {
    int gcd(int a, int b) {
        while (b != 0) { int t = a % b; a = b; b = t; }
        return a;
    }
    public boolean isGoodArray(int[] nums) {
        int g = nums[0];
        for (int i = 1; i < nums.length; i++) g = gcd(g, nums[i]);
        return g == 1;
    }
}
int gcd(int a, int b) {
    while (b != 0) { int t = a % b; a = b; b = t; }
    return a;
}
bool isGoodArray(vector<int>& nums) {
    int g = nums[0];
    for (int i = 1; i < (int)nums.size(); i++) g = gcd(g, nums[i]);
    return g == 1;
}
Time: O(n log m) Space: O(1)