Find the Number of Subsequences With Equal GCD Problem
Description
LeetCode Problem 3336.
You are given an integer array nums.
Your task is to find the number of pairs of non-empty subsequences (seq1, seq2) of nums that satisfy the following conditions:
- The subsequences
seq1andseq2are disjoint, meaning no index ofnumsis common between them. - The GCD of the elements of
seq1is equal to the GCD of the elements ofseq2.
Return the total number of such pairs.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,2,3,4]
Output: 10
Explanation:
The subsequence pairs which have the GCD of their elements equal to 1 are:
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
- ([1, 2, 3, 4], [1, 2, 3, 4])
Example 2:
Input: nums = [10,20,30]
Output: 2
Explanation:
The subsequence pairs which have the GCD of their elements equal to 10 are:
- ([10, 20, 30], [10, 20, 30])
- ([10, 20, 30], [10, 20, 30])
Example 3:
Input: nums = [1,1,1,1]
Output: 50
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 200
Solution
Approach: Memoized search over (gcd1, gcd2)
Process the elements one by one. Each element is skipped, put into the first subsequence, or put into the second one, so the state is (i, j, k): the first i elements are decided, the gcd of the first subsequence is j and that of the second is k. An empty subsequence has gcd 0 and gcd(x, 0) = x, so 0 works as the starting value.
After all elements are placed (i < 0 in the recursive form) the state counts as 1 when j == k. The three choices lead to dfs(i - 1, j, k), dfs(i - 1, gcd(nums[i], j), k) and dfs(i - 1, j, gcd(nums[i], k)). The start dfs(n - 1, 0, 0) also counts the pair of two empty subsequences, so subtract 1 (modulo 10^9 + 7).
Complexity: O(n * m^2 * log m) time and O(n * m^2) space, where m is the largest value.
from math import gcd
from functools import lru_cache
class Solution:
def subsequencePairCount(self, nums: List[int]) -> int:
@lru_cache(None)
def dfs(i: int, j: int, k: int) -> int:
if i < 0:
return int(j == k)
return (
dfs(i - 1, j, k)
+ dfs(i - 1, gcd(nums[i], j), k)
+ dfs(i - 1, j, gcd(nums[i], k))
) % mod
mod = 10**9 + 7
return (dfs(len(nums) - 1, 0, 0) - 1) % mod