Taro Logo

Sum of Beautiful Subsequences

Hard
Asked by:
Infosys
0 views
Topics:
ArraysDynamic Programming

You are given an integer array nums of length n.

For every positive integer g, we define the beauty of g as the product of g and the number of strictly increasing subsequences of nums whose greatest common divisor (GCD) is exactly g.

Return the sum of beauty values for all positive integers g.

Since the answer could be very large, return it modulo 109 + 7.

Example 1:

Input: nums = [1,2,3]

Output: 10

Explanation:

All strictly increasing subsequences and their GCDs are:

Subsequence GCD
[1] 1
[2] 2
[3] 3
[1,2] 1
[1,3] 1
[2,3] 1
[1,2,3] 1

Calculating beauty for each GCD:

GCD Count of subsequences Beauty (GCD × Count)
1 5 1 × 5 = 5
2 1 2 × 1 = 2
3 1 3 × 1 = 3

Total beauty is 5 + 2 + 3 = 10.

Example 2:

Input: nums = [4,6]

Output: 12

Explanation:

All strictly increasing subsequences and their GCDs are:

Subsequence GCD
[4] 4
[6] 6
[4,6] 2

Calculating beauty for each GCD:

GCD Count of subsequences Beauty (GCD × Count)
2 1 2 × 1 = 2
4 1 4 × 1 = 4
6 1 6 × 1 = 6

Total beauty is 2 + 4 + 6 = 12.

Constraints:

  • 1 <= n == nums.length <= 104
  • 1 <= nums[i] <= 7 * 104

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 is the expected range of the array length and the values of the elements in `nums`, and can they include negative numbers or zeros?
  2. How should we handle duplicate values in the input array regarding the strictly increasing subsequence condition (e.g., does 'strictly increasing' mean $a_i < a_j$ or can values be equal)?
  3. If the total sum of all beautiful subsequences exceeds the maximum limit of a standard integer, should we return the result modulo a specific number (like $10^9 + 7$), or use a larger data type?
  4. What should be returned if there are no valid subsequences of length at least $k$ (e.g., should it return $0$)?
  5. Could $k$ be larger than the length of the input array `nums`, and how should that edge case be handled?

Brute Force Solution

Approach

This problem computes the sum of beauty across all possible greatest common divisors of strictly increasing subsequences. For each integer, we first calculate the total number of strictly increasing subsequences consisting only of its multiples. Finally, we apply Mobius inversion or backward subtraction to find the exact number of subsequences for each greatest common divisor and accumulate their beauty.

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

  1. Find the maximum value present in the array and group array indices by their corresponding values.
  2. Iterate through each candidate divisor and gather all elements in the array that are divisible by it in their original array order.
  3. Use a Binary Indexed Tree to compute the number of strictly increasing subsequences whose elements are multiples of the current divisor.
  4. Work backwards from the maximum value down to 1 to subtract counts of higher multiples, obtaining the count of subsequences with that exact greatest common divisor.
  5. Multiply each exact count by its greatest common divisor, sum them together modulo 10^9 + 7, and return the result.

Code Implementation

def sum_of_beautiful_subsequences(nums):
    MOD = 10**9 + 7
    max_val = max(nums)
    
    # Store indices for each distinct value in the array
    positions_by_val = {}
    for index, val in enumerate(nums):
        if val not in positions_by_val:
            positions_by_val[val] = []
        positions_by_val[val].append(index)
    
    counts_multiple = [0] * (max_val + 1)
    
    # Count strictly increasing subsequences whose elements are multiples of each candidate divisor
    for divisor in range(1, max_val + 1):
        multiples = []
        for multiple in range(divisor, max_val + 1, divisor):
            if multiple in positions_by_val:
                multiples.append(multiple)
        
        if not multiples:
            continue
            
        items = []
        for multiple in multiples:
            for index in positions_by_val[multiple]:
                items.append((index, multiple))
        
        items.sort(key=lambda pair: pair[0])
        
        bit = {}
        total_for_divisor = 0
        
        for _, multiple in items:
            val_query = multiple - 1
            sub_sum = 0
            curr_idx = val_query
            while curr_idx > 0:
                if curr_idx in bit:
                    sub_sum = (sub_sum + bit[curr_idx]) % MOD
                curr_idx -= curr_idx & (-curr_idx)
            
            ways_ending_here = (sub_sum + 1) % MOD
            total_for_divisor = (total_for_divisor + ways_ending_here) % MOD
            
            curr_update = multiple
            while curr_update <= max_val:
                bit[curr_update] = (bit.get(curr_update, 0) + ways_ending_here) % MOD
                curr_update += curr_update & (-curr_update)
        
        counts_multiple[divisor] = total_for_divisor
    
    # Use inclusion-exclusion to obtain the exact count for each greatest common divisor
    exact_counts = [0] * (max_val + 1)
    total_beauty = 0
    for divisor in range(max_val, 0, -1):
        current_count = counts_multiple[divisor]
        for multiple in range(2 * divisor, max_val + 1, divisor):
            current_count = (current_count - exact_counts[multiple]) % MOD
        exact_counts[divisor] = current_count
        total_beauty = (total_beauty + divisor * current_count) % MOD
        
    return (total_beauty % MOD + MOD) % MOD

Big(O) Analysis

Time Complexity
O(M * log(M) * log(M) + N * log(N)) – For each divisor, filtering and gathering multiples along with updating the Binary Indexed Tree processes elements proportional to their frequency across harmonic divisors, resulting in overall near-linearithmic time relative to the sum of divisor frequencies.
Space Complexity
O(N + M) – We store positions of elements in lists and maintain auxiliary arrays of size proportional to the maximum value in nums.

Optimal Solution

Approach

The problem asks for the sum of beauty values over all possible GCDs of strictly increasing subsequences. We can first compute the number of strictly increasing subsequences composed exclusively of multiples of each candidate divisor. Finally, we use Möbius inversion or backward inclusion-exclusion to isolate the counts for exact GCDs and compute the total beauty.

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

  1. Group array indices by their values to efficiently retrieve elements that are multiples of each divisor.
  2. Iterate over each divisor and gather all elements in the array that are divisible by it, keeping their original relative order.
  3. Use a Fenwick tree to count all strictly increasing subsequences formed by those multiples in O(k log k) time.
  4. Store the total strictly increasing subsequences formed by multiples of each divisor.
  5. Process divisors in descending order using inclusion-exclusion to determine the count of subsequences with an exact GCD.
  6. Accumulate the product of each divisor and its exact subsequence count modulo 10^9 + 7 and return the result.

Code Implementation

def sum_of_beautiful_subsequences(nums: list[int]) -> int:
    modulo = 10**9 + 7
    max_val = max(nums)
    # Map each value to its indices in nums
    value_to_indices = [[] for _ in range(max_val + 1)]
    for index, val in enumerate(nums):
        value_to_indices[val].append(index)
    
    subseq_count_multiple = [0] * (max_val + 1)
    
    # Calculate number of strictly increasing subsequences whose elements are multiples of g
    for divisor in range(1, max_val + 1):
        multiples_indices = []
        for multiple in range(divisor, max_val + 1, divisor):
            for idx in value_to_indices[multiple]:
                multiples_indices.append((idx, multiple))
        
        if not multiples_indices:
            continue
            
        multiples_indices.sort(key=lambda pair: pair[0])
        unique_vals = sorted(list(set(multiple for idx, multiple in multiples_indices)))
        val_to_rank = {val: rank + 1 for rank, val in enumerate(unique_vals)}
        fenwick_tree = [0] * (len(unique_vals) + 1)
        
        def query(idx_rank):
            total = 0
            curr = idx_rank
            while curr > 0:
                total = (total + fenwick_tree[curr]) % modulo
                curr -= curr & -curr
            return total
            
        def update(idx_rank, delta):
            curr = idx_rank
            while curr < len(fenwick_tree):
                fenwick_tree[curr] = (fenwick_tree[curr] + delta) % modulo
                curr += curr & -curr
        
        # Count increasing subsequences using a Fenwick tree
        total_subsequences = 0
        for idx, val in multiples_indices:
            rank = val_to_rank[val]
            count_smaller = query(rank - 1)
            new_subsequences = (count_smaller + 1) % modulo
            update(rank, new_subsequences)
            total_subsequences = (total_subsequences + new_subsequences) % modulo
            
        subseq_count_multiple[divisor] = total_subsequences
        
    exact_gcd_count = [0] * (max_val + 1)
    total_beauty = 0
    # Use inclusion-exclusion to find exact GCD counts and accumulate beauty
    for divisor in range(max_val, 0, -1):
        count = subseq_count_multiple[divisor]
        for multiple in range(2 * divisor, max_val + 1, divisor):
            count = (count - exact_gcd_count[multiple]) % modulo
        exact_gcd_count[divisor] = count
        total_beauty = (total_beauty + divisor * count) % modulo
        
    return (total_beauty % modulo + modulo) % modulo

Big(O) Analysis

Time Complexity
O(M log M * log n) – For each divisor g up to M (maximum element in nums), we gather all multiples which takes sum of (N_g log N_g) across all g where N_g is the frequency of multiples. The total number of elements across all divisors is bounded by M log M, and using a Fenwick tree on each adds a logarithmic factor.
Space Complexity
O(N + M) – We store index lists for numbers up to M, which takes O(N + M) space. The Fenwick tree and supporting arrays for each divisor take space proportional to the count of unique multiples, bounded by O(min(N, M)).

Edge Cases

Array length is less than k
How to Handle:
Return a sum of zero since no valid subsequence can meet the minimum length requirement.
Array contains duplicate values
How to Handle:
Strictly increasing condition naturally prevents selecting equal elements in a valid subsequence.
Array contains negative numbers and zeros
How to Handle:
Comparison logic handles signs correctly as long as elements remain strictly greater than the previous.
No strictly increasing subsequence of length k exists
How to Handle:
Return zero as the final accumulated sum since no valid subsequences are found.
Maximum possible inputs and large subset combinations
How to Handle:
Use dynamic programming with coordinate compression or Fenwick trees to optimize performance and prevent timeouts.
Integer overflow during sum accumulation
How to Handle:
Use 64-bit integers or modulo arithmetic if specified to accommodate extremely large sums.
Array is already strictly sorted in ascending order
How to Handle:
All possible subsequences of length at least k are valid and must be counted efficiently.