Intuition¶
The answer depends only on the minimum and maximum values in nums — every other
element is ignored. Compute those two extremes in one pass, then take their GCD
with the Euclidean algorithm.
Approach: Min/Max + Euclidean GCD¶
- Find the smallest and largest elements of
nums. - Return
gcd(smallest, largest)via repeated modulo until the remainder is 0.
Complexity¶
- Time complexity: $$O(n + \log A)$$, where
nisnums.lengthandAis the maximum value — one linear scan plus Euclidean GCD. - Space complexity: $$O(1)$$ extra space.
Code¶
Go¶
import "slices"
func gcd(a, b int) int {
for b != 0 {
r := a % b
a, b = b, r
}
return a
}
func findGCD(nums []int) int {
smallest, largest := slices.Max(nums), slices.Min(nums)
return gcd(smallest, largest)
}