Find Greatest Common Divisor of Array - Problem

Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.

The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.

Input & Output

Example 1 — Basic Array
$ Input: nums = [2,5,6,9,10]
Output: 2
💡 Note: The smallest number is 2, the largest is 10. GCD(2, 10) = 2 since 2 divides both 2 and 10 evenly.
Example 2 — Small Array
$ Input: nums = [7,5,6,8,3]
Output: 1
💡 Note: The smallest number is 3, the largest is 8. GCD(3, 8) = 1 since they share no common divisors other than 1.
Example 3 — Two Elements
$ Input: nums = [3,3]
Output: 3
💡 Note: Both minimum and maximum are 3. GCD(3, 3) = 3.

Constraints

  • 2 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Find Greatest Common Divisor of Array INPUT nums = [2, 5, 6, 9, 10] 2 5 6 9 10 2 MIN 10 MAX Find GCD of: min=2, max=10 EUCLIDEAN ALGORITHM 1 Find min and max min=2, max=10 2 Apply GCD(a,b) GCD(10, 2) 3 Divide larger by smaller 10 % 2 = 0 4 Remainder is 0 Return divisor: 2 Euclidean Steps: GCD(10, 2): 10 = 2 x 5 + 0 remainder = 0 GCD = 2 FINAL RESULT Greatest Common Divisor 2 Output: 2 Verification: 10 / 2 = 5 (OK) 2 / 2 = 1 (OK) 2 divides both evenly GCD(min, max) = GCD(2, 10) = 2 Answer Confirmed Key Insight: The Euclidean Algorithm efficiently finds GCD by repeatedly replacing the larger number with the remainder of dividing the larger by the smaller, until the remainder is 0. The last non-zero value is the GCD. Time Complexity: O(n + log(min(a,b))) | Space Complexity: O(1) TutorialsPoint - Find Greatest Common Divisor of Array | Euclidean Algorithm Approach
Asked in
Google 12 Microsoft 8 Amazon 6
23.0K Views
Medium Frequency
~10 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