Problem Description
Given an array of integers nums, count the number of ordered pairs of non-empty subsequences (seq1, seq2) such that the two subsequences are disjoint (i.e. no index is reused) and the greatest common divisor (GCD) of the numbers in seq1 equals the GCD of the numbers in seq2. Return the answer modulo 10^9+7.
Key Insights
- Recognize that each element can be assigned to either subsequence 1, subsequence 2, or to neither.
- Use dynamic programming (DP) to iterate through the array and update the current GCD for each group.
- A DP state can be defined by a pair (g1, g2) representing the GCD accumulated for subsequence 1 and subsequence 2 respectively (with 0 indicating that the subsequence is still empty).
- When processing a new element, update the state by considering adding the element to group1 (updating g1), group2 (updating g2), or skipping it (leaving both groups unchanged).
- After processing all elements, sum over all DP states where both groups are nonempty (g1, g2 ≠ 0) and have equal GCD.
- The DP avoids considering 3^n complete assignments explicitly while ensuring disjointness by construction.
Space and Time Complexity
Time Complexity: O(n * MAX_VAL^2), where n is the number of elements in nums and MAX_VAL (≈200) is the maximum possible value in nums. Space Complexity: O(MAX_VAL^2) for storing DP states.
Solution
We use a dynamic programming approach with a dictionary (or 2D array) where each state is a pair (g1, g2) indicating the current GCD for subsequence 1 and subsequence 2, respectively. Initially, both subsequences are empty (represented by 0). For each number in the array, we have three choices:
- Do not include the number in either subsequence.
- Add the number to subsequence 1, updating its GCD.
- Add the number to subsequence 2, updating its GCD. After processing all elements, we sum up the ways in all states where the GCDs are equal and nonzero (ensuring that neither subsequence is empty). This process effectively counts all ways to form a pair of disjoint subsequences meeting the desired condition.