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
Find GCD of Array ExtremesStep 1: Find Min & Max | Step 2: Calculate GCDMin: 6Max: 18GCD(6, 18) = ?Euclidean Algorithm:GCD(18, 6) โ†’ 18 % 6 = 0GCD(6, 0) โ†’ return 6Result: 66
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

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 2 โ‰ค nums.length โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 1000
  • All elements are positive integers
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~12 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen