#3336
Find the Number of Subsequences With Equal GCD
HardArrayMathDynamic ProgrammingNumber TheoryDynamic ProgrammingGCD Computation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * max_num) |
| Space | O(1) | O(max_num) |
💡
Intuition
Time O(n * max_num)Space O(max_num)
The optimal solution uses dynamic programming to count subsequences with the same GCD efficiently. Instead of generating all subsequences, we keep track of how many subsequences yield each possible GCD.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a frequency array to count subsequences for each GCD from 1 to max(nums).
- 2Step 2: For each number in nums, update the frequency array for all GCDs that can be formed with this number.
- 3Step 3: Calculate the total pairs of subsequences with equal GCD using the frequency array.
solution.py22 lines
1# Full working Python code
2from math import gcd
3from collections import defaultdict
4
5MOD = 10**9 + 7
6
7def countSubsequences(nums):
8 max_num = max(nums)
9 freq = [0] * (max_num + 1)
10 total_pairs = 0
11
12 for num in nums:
13 for g in range(max_num, 0, -1):
14 if freq[g] > 0:
15 freq[gcd(g, num)] = (freq[gcd(g, num)] + freq[g]) % MOD
16 freq[num] = (freq[num] + 1) % MOD
17
18 for g in range(1, max_num + 1):
19 if freq[g] > 1:
20 total_pairs = (total_pairs + freq[g] * (freq[g] - 1) // 2) % MOD
21
22 return total_pairsℹ
Complexity note: The time complexity is O(n * max_num) because we iterate through each number and update the GCD counts for all possible GCDs, where max_num is the maximum value in nums.
- 1The GCD of a set of numbers can be computed incrementally, allowing us to build upon previous results.
- 2Counting subsequences with the same GCD can be efficiently managed using a frequency array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.