#1819
Number of Different Subsequences GCDs
HardArrayMathCountingNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m log m) |
| Space | O(1) | O(m) |
💡
Intuition
Time O(n + m log m)Space O(m)
Instead of generating all subsequences, we can determine the possible GCDs directly by checking divisors of the maximum number in the array. This is efficient because it reduces the problem to counting how many numbers in the array are divisible by each potential GCD.
⚙️
Algorithm
5 steps- 1Step 1: Find the maximum number in the array.
- 2Step 2: Create a frequency array to count occurrences of each number up to the maximum number.
- 3Step 3: Iterate through each number from 1 to the maximum number and check if it can be a GCD by counting how many numbers in the array are divisible by it.
- 4Step 4: If a number can be a GCD, add it to a set to track unique GCDs.
- 5Step 5: Return the size of the set as the result.
solution.py13 lines
1def countDifferentGCDs(nums):
2 max_num = max(nums)
3 freq = [0] * (max_num + 1)
4 for num in nums:
5 freq[num] += 1
6 gcd_set = set()
7 for g in range(1, max_num + 1):
8 count = 0
9 for multiple in range(g, max_num + 1, g):
10 count += freq[multiple]
11 if count > 0:
12 gcd_set.add(g)
13 return len(gcd_set)ℹ
Complexity note: The time complexity is O(n + m log m) where n is the length of the input array and m is the maximum number in the array. The space complexity is O(m) for the frequency array.
- 1Understanding the properties of GCD can help reduce the problem space significantly.
- 2Using a frequency array allows us to efficiently count multiples and potential GCDs.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.