LeetCode 1250: Check If It Is a Good Array Solution
Master LeetCode problem 1250 (Check If It Is a Good Array), a hard 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.
1250. Check If It Is a Good Array
Problem Explanation
Explanation
To determine if an array is "good", we need to check if there exists a subset of the array elements such that the sum of the subset elements can be manipulated to equal 1. This can be done by using the fact that the GCD (greatest common divisor) of all the array elements should be 1. If the GCD of all elements is 1, it means we can find a linear combination of these elements to form 1.
Here is the algorithm:
- Compute the GCD of all elements in the array.
- If the GCD is 1, return True. Otherwise, return False.
Time complexity: O(n * log(max(nums))), where n is the number of elements in the array and max(nums) is the maximum value in the array. Space complexity: O(1)
Solution Code
class Solution {
public boolean isGoodArray(int[] nums) {
int gcd = nums[0];
for (int num : nums) {
gcd = gcd(gcd, num);
if (gcd == 1) {
return true;
}
}
return gcd == 1;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1250 (Check If It Is a Good Array)?
This page provides optimized solutions for LeetCode problem 1250 (Check If It Is a Good 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 1250 (Check If It Is a Good Array)?
The time complexity for LeetCode 1250 (Check If It Is a Good Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1250 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1250 in Java, C++, or Python.