LeetCode 1979: Find Greatest Common Divisor of Array Solution
Master LeetCode problem 1979 (Find Greatest Common Divisor of Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1979. Find Greatest Common Divisor of Array
Problem Explanation
Explanation
To find the greatest common divisor of the smallest and largest numbers in the given array, we can use the Euclidean algorithm to efficiently compute the greatest common divisor of two numbers. First, we find the smallest and largest numbers in the array. Then, we repeatedly apply the Euclidean algorithm to find the greatest common divisor of these two numbers.
- Find the smallest and largest numbers in the array.
- Apply the Euclidean algorithm to find the greatest common divisor of the smallest and largest numbers.
Time Complexity:
Finding the smallest and largest numbers: O(n)
Applying Euclidean algorithm: O(log(min(a, b))) where a and b are the smallest and largest numbers respectively.
Overall time complexity: O(n + log(min(a, b)))
Space Complexity:
We are not using any extra space apart from the input array.
Space complexity: O(1)
Solution Code
class Solution {
public int findGCD(int[] nums) {
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
for (int num : nums) {
min = Math.min(min, num);
max = Math.max(max, num);
}
return gcd(min, max);
}
private int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1979 (Find Greatest Common Divisor of Array)?
This page provides optimized solutions for LeetCode problem 1979 (Find Greatest Common Divisor of Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1979 (Find Greatest Common Divisor of Array)?
The time complexity for LeetCode 1979 (Find Greatest Common Divisor of Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1979 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1979 in Java, C++, or Python.