Find Greatest Common Divisor of Array (LeetCode 1979): Solution and Explanation
Given an integer array nums, return the greatest common divisor of its smallest and largest values. Every other element is irrelevant, so the problem is a min and max scan followed by a two-number gcd.
Intuition
Read the statement carefully: it asks for the gcd of only two numbers, the minimum and the maximum. One pass over the array finds both, and the rest of the values can be ignored.
For the gcd itself, trying every divisor from min down to 1 works for values up to 1000, but Euclid's algorithm is the standard tool. Any number that divides both a and b also divides a - b, and so it divides a % b. That means gcd(a, b) = gcd(b, a % b), and since the remainder is smaller than b, the pair shrinks quickly until the remainder is 0. At that point the other number is the gcd.
There is a nice picture for this. Take an a by b rectangle and cut off as many b by b squares as fit. What is left is a b by a % b strip. Keep cutting the largest squares from the leftover strip. The last square size that tiles the remainder exactly also tiles the whole rectangle, and it is the largest square that does, which is the gcd.
Approach: Min and max, then Euclid's algorithm
- Set
a = max(nums)andb = min(nums). - While
b != 0, replace the pair with(b, a % b). - When
breaches 0, returna.
Step-by-step example
nums = [2,5,6,9,10]
- Scanning the array gives
min = 2andmax = 10, soa = 10andb = 2. - b is not 0: 10 = 5 × 2 + 0, so the pair becomes (2, 0). Five 2 by 2 squares fill the 10 by 2 rectangle exactly.
- b is 0, so the loop stops and the function returns 2.
Code: Python, Java, C++
1class Solution:
2 def findGCD(self, nums: List[int]) -> int:
3 a, b = max(nums), min(nums)
4 while b:
5 a, b = b, a % b
6 return a1class Solution {
2 public int findGCD(int[] nums) {
3 int a = Arrays.stream(nums).max().getAsInt(), b = Arrays.stream(nums).min().getAsInt();
4 while (b != 0) {
5 int r = a % b; a = b; b = r;
6 }
7 return a;
8 }
9}1class Solution {
2public:
3 int findGCD(vector<int>& nums) {
4 int a = *max_element(nums.begin(), nums.end()), b = *min_element(nums.begin(), nums.end());
5 while (b != 0) {
6 int r = a % b; a = b; b = r;
7 }
8 return a;
9 }
10};Time and space complexity
O(n + log m)
Finding the minimum and maximum takes one pass over the n values, and Euclid's algorithm takes O(log m) steps where m is the maximum value.
O(1)
Only a handful of integers are stored.
Other approaches
Try every divisor (time O(n + m), space O(1))
Count d down from min to 1 and return the first d that divides both min and max. Simple and fast enough for values up to 1000, but it does O(m) work for the gcd part.
Library gcd (time O(n + log m), space O(1))
Python's math.gcd, C++ std::gcd and Java's BigInteger.gcd do the same job. They are fine in practice, but interviewers usually want to see Euclid's algorithm written out.
Sort first (time O(n log n), space O(1) to O(n))
Sort the array and take the first and last elements. It works but costs O(n log n) for information a single scan already gives.
Common mistakes
- Computing the gcd of the whole array instead of only the minimum and maximum. For [4, 6, 8] the answer is gcd(4, 8) = 4, while the gcd of all three values is 2.
- Writing the Euclid loop with the wrong update order, such as
a = b; b = a % b, which computes b % b = 0 and stops after one step with the wrong answer. - Starting the loop with a zero divisor. Here every value is at least 1, so
bstarts positive, but a general gcd function should handle 0.
Frequently asked questions
Why is gcd(a, b) equal to gcd(b, a % b)?
a % b equals a - q·b for some integer q. Any number dividing a and b divides a - q·b, and any number dividing b and a - q·b divides a. So both pairs have exactly the same common divisors and the same greatest one.
Does it matter whether I start with (max, min) or (min, max)?
No. If a < b then a % b = a, so the first step simply swaps them. Starting with the larger number just saves that step.
How many steps does Euclid's algorithm take?
O(log m) for numbers up to m. The worst case is two consecutive Fibonacci numbers, such as 233 and 377, where each quotient is 1.
What are the time and space complexity?
O(n + log m) time, dominated by the min and max scan, and O(1) extra space.