#1250

Check If It Is a Good Array

Hard
ArrayMathNumber TheoryNumber TheoryGCDMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages the mathematical property that a linear combination of integers can yield a specific integer (like 1) if the greatest common divisor (gcd) of the integers is 1. This is based on Bézout's lemma.

⚙️

Algorithm

2 steps
  1. 1Step 1: Compute the gcd of all elements in the array.
  2. 2Step 2: If the gcd is 1, return True; otherwise, return False.
solution.py6 lines
1# Full working Python code
2import math
3from functools import reduce
4
5def is_good_array(nums):
6    return reduce(math.gcd, nums) == 1

Complexity note: The time complexity is O(n) because we are calculating the gcd of n numbers in a single pass. The space complexity is O(1) since we are only using a few variables.

  • 1The gcd of the array elements determines if we can form the sum of 1.
  • 2Using mathematical properties can significantly reduce the complexity of the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.