Check If It Is a Good Array - Problem
Check If It Is a Good Array
Given an array
This is essentially asking: Can we find integers a₁, a₂, ..., aₙ such that a₁×nums[0] + a₂×nums[1] + ... + aₙ×nums[n-1] = 1?
🎯 Goal: Return
Mathematical Insight: This problem is rooted in number theory - specifically Bézout's identity, which states that a linear combination of integers can produce 1 if and only if their greatest common divisor (GCD) is 1.
Given an array
nums of positive integers, your task is to determine if it's a "good" array. An array is considered good if you can select any subset of its elements, multiply each selected element by any integer (positive, negative, or zero), and make the sum equal to exactly 1.This is essentially asking: Can we find integers a₁, a₂, ..., aₙ such that a₁×nums[0] + a₂×nums[1] + ... + aₙ×nums[n-1] = 1?
🎯 Goal: Return
true if the array is good, false otherwise.Mathematical Insight: This problem is rooted in number theory - specifically Bézout's identity, which states that a linear combination of integers can produce 1 if and only if their greatest common divisor (GCD) is 1.
Input & Output
example_1.py — Basic Good Array
$
Input:
nums = [12, 30, 15]
›
Output:
false
💡 Note:
GCD(12, 30, 15) = 3 ≠ 1, so no linear combination can equal 1. The array is not good.
example_2.py — Simple Good Array
$
Input:
nums = [6, 10, 15]
›
Output:
true
💡 Note:
GCD(6, 10, 15) = 1, so we can find integers to make sum = 1. For example: 4×6 + (-1)×10 + (-1)×15 = 24 - 10 - 15 = -1... Actually, by Bézout's identity, a solution exists.
example_3.py — Single Element
$
Input:
nums = [1]
›
Output:
true
💡 Note:
GCD(1) = 1, and we can simply use 1×1 = 1. Single element arrays with value 1 are always good.
Visualization
Tap to expand
Understanding the Visualization
1
The Problem
Find integers a₁, a₂, ..., aₙ such that a₁×nums[0] + a₂×nums[1] + ... = 1
2
Bézout's Identity
This equation has integer solutions iff gcd(nums[0], nums[1], ...) = 1
3
Algorithm
Compute GCD of all array elements in linear time
4
Result
Return true if GCD equals 1, false otherwise
Key Takeaway
🎯 Key Insight: Instead of trying infinite combinations, use the mathematical fact that linear combinations can produce 1 if and only if the GCD of all numbers is 1. This transforms an intractable problem into a simple O(n) algorithm!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array, GCD computation is effectively constant for practical numbers
✓ Linear Growth
Space Complexity
O(1)
Only storing the running GCD value
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 103
- 1 ≤ nums[i] ≤ 109
- All integers in nums are positive
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code