Leetcode 1979: Find Greatest Common Divisor of Array

grid47
grid47
Exploring patterns and algorithms
Apr 23, 2024 5 min read

Given an array of integers, your task is to compute the greatest common divisor (GCD) of the smallest and largest elements in the array.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` where each element is a positive integer.
Example: nums = [12, 30, 50, 60, 80]
Constraints:
• 2 <= nums.length <= 1000
• 1 <= nums[i] <= 1000
Output: The output should be the greatest common divisor of the smallest and largest number in the array.
Example: Output: 10
Constraints:
• The result should be an integer.
Goal: Find the GCD of the smallest and largest number in the array.
Steps:
• Step 1: Find the smallest and largest numbers in the array.
• Step 2: Compute the greatest common divisor (GCD) of these two numbers using the Euclidean algorithm.
• Step 3: Return the GCD as the result.
Goal: The solution must be efficient enough to handle the problem's constraints.
Steps:
• The length of the array is at least 2 and at most 1000.
• Each element in the array is a positive integer between 1 and 1000.
Assumptions:
• The input array contains at least two integers.
• The GCD of the smallest and largest integers will be calculated.
Input: Input: nums = [12, 30, 50, 60, 80]
Explanation: In this example, the smallest number is 12, and the largest number is 80. The greatest common divisor of 12 and 80 is 4.

Input: Input: nums = [7, 5, 6, 8, 3]
Explanation: The smallest number is 3, and the largest number is 8. The GCD of 3 and 8 is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus