#1979
Find Greatest Common Divisor of Array
EasyArrayMathNumber TheoryMathArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the mathematical property of the greatest common divisor (GCD) and uses the built-in GCD function to compute the result efficiently.
⚙️
Algorithm
3 steps- 1Step 1: Find the minimum (mn) and maximum (mx) values in the array in one pass.
- 2Step 2: Use the built-in GCD function to compute the GCD of mn and mx.
- 3Step 3: Return the result.
solution.py7 lines
1# Full working Python code
2import math
3
4def findGCD(nums):
5 mn = min(nums)
6 mx = max(nums)
7 return math.gcd(mn, mx)ℹ
Complexity note: The time complexity is O(n) because we find the min and max in a single pass through the array. The GCD calculation is O(log(min, max)) which is efficient. The space complexity is O(1) since we only use a few variables.
- 1Finding the minimum and maximum in one pass can save time.
- 2Using built-in functions for GCD can optimize performance significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.