Find Greatest Common Divisor of Array - Problem
Given an integer array nums, your task is to find the greatest common divisor (GCD) of the smallest and largest numbers in the array.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers without leaving a remainder.
Example: If we have the array [2, 5, 6, 9, 10], the smallest number is 2 and the largest is 10. The GCD of 2 and 10 is 2, since 2 is the largest number that divides both 2 and 10 evenly.
Goal: Return the GCD of the minimum and maximum values in the given array.
Input & Output
example_1.py โ Basic Case
$
Input:
[2, 5, 6, 9, 10]
โบ
Output:
2
๐ก Note:
The smallest number is 2 and the largest is 10. GCD(2, 10) = 2 because 2 is the largest number that divides both 2 and 10 evenly.
example_2.py โ Coprime Numbers
$
Input:
[7, 5, 6, 8, 3]
โบ
Output:
1
๐ก Note:
The smallest number is 3 and the largest is 8. GCD(3, 8) = 1 because 3 and 8 share no common factors other than 1.
example_3.py โ Single Element
$
Input:
[10]
โบ
Output:
10
๐ก Note:
When there's only one element, both min and max are the same number (10), so GCD(10, 10) = 10.
Visualization
Tap to expand
Understanding the Visualization
1
Scan Array
Find the minimum and maximum values in one pass
2
Apply Euclidean Algorithm
Use the mathematical formula: GCD(a,b) = GCD(b, a mod b)
3
Return Result
When one number becomes 0, return the other as GCD
Key Takeaway
๐ฏ Key Insight: We only need the array's extreme values (min/max), then the Euclidean algorithm efficiently finds their GCD in logarithmic time!
Time & Space Complexity
Time Complexity
O(n + log(min(a,b)))
O(n) to find min/max using built-in functions, O(log(min(a,b))) for Euclidean algorithm
โก Linearithmic
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 2 โค nums.length โค 1000
- 1 โค nums[i] โค 1000
- All elements are positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code