Python 1250.py
class Solution:
def isGoodArray(self, nums: List[int]) -> bool:
# this is a pure math problem
# don't know why it's on Leetcode ...
# select two numbers a and b
# we need to find x and y such that ax + by = 1
# this is only possible if they share no prime factor
return gcd(*nums) == 1
Difficulty
and has an acceptance rate of about 66% (60k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Number Theory
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method isGoodArray. The method determines whether a given integer array nums satisfies a specific number-theoretic condition: the existence of integer coefficients x and y such that a linear combination of any two selected elements equals 1. This condition is equivalent to checking whether the greatest common divisor (GCD) of all elements in the array is 1. The method returns a Boolean result reflecting this property.
Core Logic
The essential computation is performed in a single return statement:
return gcd(*nums) == 1
The expression gcd(*nums) invokes the gcd function with the entire contents of nums unpacked as separate arguments. The gcd function iteratively computes the greatest common divisor across all supplied integers. The comparison with 1 yields True precisely when the collective GCD is unity, indicating that the array elements are coprime in aggregate.
Key Steps
Import and Preparation
Although not shown, the code relies on the standard library math.gcd function, which is capable of handling an arbitrary number of integer arguments when supplied via unpacking. This eliminates the need for explicit loops or auxiliary data structures.
GCD Computation
The unpacking operator * expands the list nums into positional arguments for gcd. Internally, gcd applies the Euclidean algorithm pairwise, efficiently reducing the problem to a single integer result. The built-in implementation is highly optimized in C, providing fast execution even for large inputs.
Boolean Evaluation
The equality check == 1 converts the numeric GCD result into a Boolean value. If the GCD equals one, the method returns True; otherwise, it returns False. This direct comparison avoids additional conditional branches.
Edge Cases Handled
When nums contains a single element, the unpacking passes that element alone to gcd, and the function correctly returns the absolute value of that element. Consequently, an array [1] yields True, while [0] yields False because gcd(0) is 0.
If the array includes zero values alongside non-zero integers, the GCD calculation treats zero as a neutral element: gcd(0, a) = |a|. Therefore, an array such as [0, 5, 7] results in a GCD of 1 only if the non-zero elements are coprime.
Negative numbers are also accommodated because gcd operates on absolute values. An input like [-3, 6] yields a GCD of 3, leading to a False outcome, consistent with the mathematical definition.
An empty list would raise a TypeError due to missing arguments for gcd; however, typical usage on LeetCode guarantees at least one element, so the method functions correctly under the expected contract.
Performance Optimizations
The implementation leverages the native math.gcd function, which is written in C and benefits from low-level optimizations such as loop unrolling and branch prediction. By passing all numbers at once via unpacking, the code avoids the overhead of explicit Python loops and intermediate variable assignments. This approach minimizes interpreter dispatch and memory allocation, resulting in a concise and fast execution path.
Additionally, the early termination property of the Euclidean algorithm is inherent in the built-in gcd. If at any stage the intermediate GCD becomes 1, subsequent iterations cease further computation, effectively short-circuiting the process without extra code.
Overall, the method achieves the desired result with minimal Python-level logic, relying on highly tuned library routines to handle the heavy lifting.
ELI5 - Simplified Explanation
Imagine you have a big treasure box full of different numbers. This program is like a magic game that looks at all the numbers in your box to see if they share a special secret. When numbers are best friends, they can be combined in a clever way to make the number one. This piece of code reaches into the box and picks out all the numbers to see if they can work together to create that special one. It uses a math trick called the greatest common divisor. If that trick finds that the only thing the numbers have in common is the number one, then the whole box is considered good. Think of it like checking to see if a group of colorful blocks can fit together to build one perfect, tiny tower.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++ | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 892: Surface Area of 3D Shapes
- problem 1266: Minimum Time Visiting All Points
- problem 2481: Minimum Cuts to Divide a Circle
- problem 1405: Longest Happy String
- problem 1530: Number of Good Leaf Nodes Pairs
- problem 1610: Maximum Number of Visible Points
- problem 2444: Count Subarrays With Fixed Bounds
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality