LeetCode 1819: Number of Different Subsequences GCDs Solution
Master LeetCode problem 1819 (Number of Different Subsequences GCDs), 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.
1819. Number of Different Subsequences GCDs
Problem Explanation
Explanation:
To solve this problem, we need to find the number of different GCDs among all non-empty subsequences of the given array nums. We can approach this problem by iterating through each possible GCD value from 1 to the maximum value in nums and check if that GCD can be formed by any subsequence of nums. We can use the concept of the greatest common divisor (GCD) to find the GCD of subsequences efficiently.
- Initialize a set to store all possible GCD values.
- Iterate through all numbers in
numsand add them to the set. - For each number in
nums, iterate through all possible GCD values from 1 to the maximum number innums. - Check if the GCD of the current number and the current possible GCD is in the set, if so, add it to the set.
- Repeat step 4 for all numbers in
nums. - Finally, return the size of the set as the result.
Time Complexity: O(n * sqrt(max(nums))) where n is the length of nums and max(nums) is the maximum value in nums.
Space Complexity: O(sqrt(max(nums))) for storing the set of GCD values.
Solution Code
class Solution {
public int countDifferentSubsequenceGCDs(int[] nums) {
Set<Integer> gcds = new HashSet<>();
int maxNum = Arrays.stream(nums).max().getAsInt();
for (int num : nums) {
gcds.add(num);
}
for (int num : nums) {
for (int i = 1; i <= maxNum; i++) {
if (gcds.contains(i)) {
gcds.add(gcd(num, i));
}
}
}
return gcds.size();
}
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 1819 (Number of Different Subsequences GCDs)?
This page provides optimized solutions for LeetCode problem 1819 (Number of Different Subsequences GCDs) 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 1819 (Number of Different Subsequences GCDs)?
The time complexity for LeetCode 1819 (Number of Different Subsequences GCDs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1819 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1819 in Java, C++, or Python.