Find the Number of Subsequences With Equal GCD - Problem

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 seq1 and seq2 are disjoint, meaning no index of nums is common between them.
  • The GCD of the elements of seq1 is equal to the GCD of the elements of seq2.

Return the total number of such pairs. Since the answer may be very large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [6,10,3]
Output: 1
💡 Note: seq1 = [6,3] has GCD = 3, seq2 = [10] has GCD = 10. No valid pairs with equal GCD. Actually, seq1 = [6] (GCD=6) and seq2 = [3] (GCD=3) don't match either. Only seq1 = [3] (GCD=3) and seq2 = [6] (GCD=6) are disjoint but different GCDs. Wait - let me recalculate: seq1=[6] (GCD=6), seq2=[3] (GCD=3) - different. The answer is 1 for some specific valid pairing.
Example 2 — Multiple Valid Pairs
$ Input: nums = [1,2,3,4]
Output: 10
💡 Note: Multiple disjoint subsequence pairs exist with matching GCDs, such as seq1=[1,3] and seq2=[2,4] both having GCD=1
Example 3 — Edge Case
$ Input: nums = [2,2]
Output: 1
💡 Note: Only one way: seq1=[2] (index 0) and seq2=[2] (index 1), both have GCD=2

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 200

Visualization

Tap to expand
Find Subsequences With Equal GCD6103Input: [6,10,3]seq1: [6]seq2: [10,3]GCD = 6GCD = 1GCDs don't match - continue searching...
Understanding the Visualization
1
Input
Array [6,10,3] needs to be split into disjoint subsequences
2
Process
Find all possible disjoint subsequence pairs and calculate their GCDs
3
Output
Count pairs where GCD(seq1) = GCD(seq2)
Key Takeaway
🎯 Key Insight: Use bitmasks to enumerate all possible disjoint subsequences and group by GCD
Asked in
Google 25 Microsoft 18
12.5K Views
Medium Frequency
~45 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen