Taro Logo

Find the Number of Subsequences With Equal GCD

#82 Most AskedHard
0 views
Topics:
ArraysDynamic Programming

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 109 + 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 <= 200
  • 1 <= nums[i] <= 200

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the size constraints of the input array and the maximum possible value of the elements within it?
  2. How should identical subsequences formed by different indices in the input array be treated—are they considered distinct subsequences or grouped together?
  3. What should be returned if the array is empty or if no valid subsequences can be formed?
  4. Since the problem asks for the total number of distinct subsequences that share the exact same GCD value, should we return the maximum count of subsequences for any single GCD, or the total count grouped by GCD, or something else?
  5. Are elements in the input array guaranteed to be positive integers, or could we encounter zeros?

Brute Force Solution

Approach

This problem requires counting pairs of disjoint subsequences with identical greatest common divisors (GCDs). We can use dynamic programming where states represent the running GCDs of the first and second subsequences. For each element in the input array, we can either skip it, append it to the first subsequence, or append it to the second subsequence.

Here's how the algorithm would work step-by-step:

  1. Find the maximum value present in the array to know the range of possible GCD values.
  2. Initialize a dictionary tracking the number of ways to form pairs of running GCDs, starting with (0, 0) having one way.
  3. Iterate through each number in the array and update the dynamic programming state by considering assigning the number to either sequence or neither.
  4. Calculate the new GCD for each subsequence choice using the standard Euclidean algorithm.
  5. Sum up the number of ways where both subsequences are non-empty and share the exact same GCD value modulo 10^9 + 7.

Code Implementation

import math

def subsequence_pair_gcd(nums):
    modulo = 10**9 + 7
    max_value = max(nums)
    # Dynamic programming table mapping (gcd1, gcd2) to the number of ways
    ways = {(0, 0): 1}
    for number in nums:
        next_ways = dict(ways)
        # Transition by placing the current number into seq1, seq2, or neither
        for (gcd_one, gcd_two), count in ways.items():
            new_gcd_one = math.gcd(gcd_one, number)
            next_pair_one = (new_gcd_one, gcd_two)
            next_ways[next_pair_one] = (next_ways.get(next_pair_one, 0) + count) % modulo
            
            new_gcd_two = math.gcd(gcd_two, number)
            next_pair_two = (gcd_one, new_gcd_two)
            next_ways[next_pair_two] = (next_ways.get(next_pair_two, 0) + count) % modulo
        ways = next_ways
    total_pairs = 0
    # Sum all configurations where both subsequences have non-zero matching GCDs
    for target_gcd in range(1, max_value + 1):
        total_pairs = (total_pairs + ways.get((target_gcd, target_gcd), 0)) % modulo
    return total_pairs

Big(O) Analysis

Time Complexity
O(N * M^2 * log(M)) – Here N is the length of nums and M is the maximum element in nums (at most 200). The number of reachable GCD pairs is at most M^2, and for each number we compute the GCD in O(log(M)) steps across the reachable states.
Space Complexity
O(M^2) – The dynamic programming dictionary stores pairs of GCD values, each ranging from 0 to M, resulting in at most (M + 1)^2 distinct state entries.

Optimal Solution

Approach

This problem asks for the number of pairs of disjoint non-empty subsequences that have the same greatest common divisor. Since the elements are small, we can track the running GCD of both subsequences using dynamic programming. For each element, we have three choices: do not include it, include it in the first subsequence, or include it in the second subsequence.

Here's how the algorithm would work step-by-step:

  1. Find the maximum value present in the array to limit the range of possible greatest common divisors.
  2. Initialize a dynamic programming state mapping pairs of running GCD values to their counts, starting with (0, 0) having a count of 1.
  3. Iterate through each number in the array, transitioning each existing state to three possibilities: skip the number, include it in the first subsequence, or include it in the second subsequence.
  4. Update the GCD states using the standard greatest common divisor function and accumulate the counts modulo 1,000,000,007.
  5. Sum the counts for all states where the first and second subsequences have matching non-zero GCDs, and return the result.

Code Implementation

import math

def subsequence_pair_count(nums: list[int]) -> int:
    modulo = 10**9 + 7
    max_val = max(nums)
    # Initialize the dynamic programming table mapping (gcd1, gcd2) to counts
    dp_table = {(0, 0): 1}
    for number in nums:
        next_dp = dp_table.copy()
        for (gcd_first, gcd_second), count in dp_table.items():
            # Option 1: add the current number to the first subsequence
            new_gcd_first = math.gcd(gcd_first, number)
            next_dp[(new_gcd_first, gcd_second)] = (next_dp.get((new_gcd_first, gcd_second), 0) + count) % modulo
            # Option 2: add the current number to the second subsequence
            new_gcd_second = math.gcd(gcd_second, number)
            next_dp[(gcd_first, new_gcd_second)] = (next_dp.get((gcd_first, new_gcd_second), 0) + count) % modulo
        dp_table = next_dp
    # Sum up valid configurations where both subsequences have equal non-zero GCD
    total_pairs = 0
    for target_gcd in range(1, max_val + 1):
        total_pairs = (total_pairs + dp_table.get((target_gcd, target_gcd), 0)) % modulo
    return total_pairs

Big(O) Analysis

Time Complexity
O(N * M^2 * log(M)) – Here, N is the length of nums (up to 200) and M is the maximum value in nums (up to 200). In the worst case, there are at most M^2 states in the DP dictionary, and processing each number takes O(log M) time per state due to the GCD operation.
Space Complexity
O(M^2) – The dynamic programming dictionary stores pairs of GCD values, each bounded by the maximum value M, resulting in at most O(M^2) distinct states stored in memory.

Edge Cases

Array with a single element
How to Handle:
Return 1 since exactly one non-empty subsequence exists with a GCD equal to that single element.
Array containing all identical values
How to Handle:
Compute combinations using powers of two minus one, mapping them directly to that single GCD value.
Large maximum values in the input array
How to Handle:
Use efficient GCD algorithms like Euclidean division alongside frequency counting to prevent performance bottlenecks.
Extremely large total number of valid subsequences
How to Handle:
Apply modulo arithmetic typically 10 to the 9th plus 7 at each addition step to prevent integer overflow.
Sparse distribution of GCD values across subsequences
How to Handle:
Utilize a hash map or bounded frequency array to store and aggregate counts only for achieved GCDs.
Inputs with many coprime elements
How to Handle:
Ensure the dynamic programming transition correctly handles gcd combinations scaling up to the array maximum.
0/257 completed