Taro Logo

Find Sum of Array Product of Magical Sequences

#221 Most AskedHard
0 views
Topics:
ArraysDynamic ProgrammingBit Manipulation

You are given two integers, m and k, and an integer array nums.

A sequence of integers seq is called magical if:
  • seq has a size of m.
  • 0 <= seq[i] < nums.length
  • The binary representation of 2seq[0] + 2seq[1] + ... + 2seq[m - 1] has k set bits.

The array product of this sequence is defined as prod(seq) = (nums[seq[0]] * nums[seq[1]] * ... * nums[seq[m - 1]]).

Return the sum of the array products for all valid magical sequences.

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

A set bit refers to a bit in the binary representation of a number that has a value of 1.

Example 1:

Input: m = 5, k = 5, nums = [1,10,100,10000,1000000]

Output: 991600007

Explanation:

All permutations of [0, 1, 2, 3, 4] are magical sequences, each with an array product of 1013.

Example 2:

Input: m = 2, k = 2, nums = [5,4,3,2,1]

Output: 170

Explanation:

The magical sequences are [0, 1], [0, 2], [0, 3], [0, 4], [1, 0], [1, 2], [1, 3], [1, 4], [2, 0], [2, 1], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [3, 4], [4, 0], [4, 1], [4, 2], and [4, 3].

Example 3:

Input: m = 1, k = 1, nums = [28]

Output: 28

Explanation:

The only magical sequence is [0].

Constraints:

  • 1 <= k <= m <= 30
  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= 108

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. How are the 'magical sequences' represented? Are they given as arrays of indices referencing the input array, or as arrays of actual values?
  2. Can elements within a single magical sequence be reused, or does each reference correspond to a distinct index in the array?
  3. What should happen if a magical sequence references an index that is out of bounds for the given array?
  4. Are negative numbers or zeros allowed in the input array, and how do they affect the product calculation?
  5. What should be returned if the predefined set of magical sequences is empty?

Brute Force Solution

Approach

The problem asks for the sum of products of sequences of indices where the sum of powers of two corresponding to the indices has exactly k set bits. Instead of choosing indices sequentially, we can group sequences by the count of each index used, which forms an addition problem in base 2. We use dynamic programming to process each index position from 0 to n - 1, keeping track of the count of used indices, the carry to the next binary digit, and the accumulated set bits.

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

  1. Precompute factorials and inverse factorials modulo 1,000,000,007 to easily determine multinomial coefficients.
  2. Precompute powers of each array element modulo 1,000,000,007 divided by the factorial of the count to facilitate product combination.
  3. Initialize dynamic programming states tracking the number of selected elements, the current arithmetic carry, and the number of set bits generated so far.
  4. Iterate through each available index in nums, branching on how many times that index is chosen, updating the carry and set bit count.
  5. After examining all indices, evaluate the remaining carry bits and accumulate all states that utilize exactly m elements and produce k set bits.
  6. Multiply the final accumulated sum by the factorial of m to account for all distinct permutations.

Code Implementation

def find_sum_of_array_product_of_magical_sequences(target_length: int, target_set_bits: int, nums: list[int]) -> int:
    MOD = 1_000_000_007
    nums_length = len(nums)
    
    # Precompute factorials and their modular inverses for multinomial coefficients
    factorials = [1] * (target_length + 1)
    for index in range(1, target_length + 1):
        factorials[index] = (factorials[index - 1] * index) % MOD
        
    inv_factorials = [1] * (target_length + 1)
    inv_factorials[target_length] = pow(factorials[target_length], MOD - 2, MOD)
    for index in range(target_length - 1, -1, -1):
        inv_factorials[index] = (inv_factorials[index + 1] * (index + 1)) % MOD
        
    # Precompute powers of each element in nums
    power_table = [[1] * (target_length + 1) for _ in range(nums_length)]
    for num_index in range(nums_length):
        current_val = nums[num_index] % MOD
        for count in range(1, target_length + 1):
            power_table[num_index][count] = (power_table[num_index][count - 1] * current_val) % MOD
            
    # dp[used_elements][current_carry][set_bits_formed]
    dp = {(0, 0, 0): 1}
    
    # Process elements position by position up to nums_length
    for num_index in range(nums_length):
        next_dp = {}
        for (used_elements, current_carry, set_bits_formed), current_prod_sum in dp.items():
            for count in range(target_length - used_elements + 1):
                total_at_bit = current_carry + count
                new_bit = total_at_bit & 1
                new_carry = total_at_bit >> 1
                new_set_bits = set_bits_formed + new_bit
                if new_set_bits > target_set_bits:
                    continue
                term = (power_table[num_index][count] * inv_factorials[count]) % MOD
                next_state = (used_elements + count, new_carry, new_set_bits)
                next_dp[next_state] = (next_dp.get(next_state, 0) + current_prod_sum * term) % MOD
        dp = next_dp
        
    total_sum = 0
    # Add remaining set bits from the carry and multiply by m factorial
    for (used_elements, carry, set_bits_formed), current_prod_sum in dp.items():
        if used_elements == target_length:
            final_bits = set_bits_formed + bin(carry).count("1")
            if final_bits == target_set_bits:
                total_sum = (total_sum + current_prod_sum) % MOD
                
    return (total_sum * factorials[target_length]) % MOD

Big(O) Analysis

Time Complexity
O(nums.length * m^3) – At each index of nums, there are at most m + 1 values for used elements, at most m values for carry, and at most k <= m values for set bits. Transitioning iterates over possible counts up to m - used_elements. Thus, the number of operations per element is bounded by O(m^3), yielding an overall time complexity of O(nums.length * m^3).
Space Complexity
O(m^3) – The dynamic programming dictionary stores reachable combinations of used elements, carry, and set bits formed. Since each dimension is bounded by m, the space complexity is O(m^3).

Optimal Solution

Approach

The problem asks for the sum of products of magical sequences of length m whose multiset of indices produces an integer with exactly k set bits when each index i is weighted as 2 to the power of i. Since order matters, each valid multiset of index counts contributes its product scaled by the multinomial coefficient. We use dynamic programming bit-by-bit from least significant position to most significant position while tracking the carry, elements consumed, and accumulated set bits.

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

  1. Precompute factorials and inverse factorials up to m to efficiently evaluate multinomial coefficients modulo 10^9 + 7.
  2. Precompute powers of each element in nums to compute products in constant time.
  3. Initialize dynamic programming state tracking elements used so far, carry into current bit position, and total set bits produced.
  4. Iterate over each index of nums, choosing how many times to include that index and propagating the bit sum and carry to the next position.
  5. After processing all array positions, resolve any remaining carry bits into the set bit total.
  6. Multiply the accumulated values by the factorial of m to account for all distinct permutations and return the result.

Code Implementation

def find_sum_of_magical_sequences(m: int, k: int, nums: list[int]) -> int:
    modulo = 1_000_000_007
    num_count = len(nums)
    # Precompute factorials and inverse factorials for combinations
    factorials = [1] * (m + 1)
    for index in range(1, m + 1):
        factorials[index] = (factorials[index - 1] * index) % modulo
    inverse_factorials = [1] * (m + 1)
    inverse_factorials[m] = pow(factorials[m], modulo - 2, modulo)
    for index in range(m - 1, -1, -1):
        inverse_factorials[index] = (inverse_factorials[index + 1] * (index + 1)) % modulo
    powers_of_nums = [[1] * (m + 1) for _ in range(num_count)]
    for idx in range(num_count):
        for count in range(1, m + 1):
            powers_of_nums[idx][count] = (powers_of_nums[idx][count - 1] * nums[idx]) % modulo
    # dp[used_elements][current_carry][set_bits]
    dp = {(0, 0, 0): 1}
    for idx in range(num_count):
        next_dp = {}
        for (used_elements, carry, set_bits), ways in dp.items():
            for count in range(m - used_elements + 1):
                total_val = carry + count
                new_bit = total_val % 2
                new_carry = total_val // 2
                new_set_bits = set_bits + new_bit
                if new_set_bits <= k:
                    weight = (ways * powers_of_nums[idx][count]) % modulo
                    weight = (weight * inverse_factorials[count]) % modulo
                    state = (used_elements + count, new_carry, new_set_bits)
                    next_dp[state] = (next_dp.get(state, 0) + weight) % modulo
        dp = next_dp
    # Finalize by propagating any remaining carry bits
    total_result = 0
    for (used_elements, carry, set_bits), ways in dp.items():
        if used_elements == m:
            final_bits = set_bits + carry.bit_count()
            if final_bits == k:
                total_result = (total_result + ways) % modulo
    total_result = (total_result * factorials[m]) % modulo
    return total_result

Big(O) Analysis

Time Complexity
O(n * m^3) – There are n elements in nums. At each step, the number of used elements is at most m + 1, the carry is at most m, and the set bits count is at most k + 1 <= m + 1. Transitioning involves iterating over count from 0 to m, leading to at most O(n * m^3) state transitions with O(1) arithmetic operations.
Space Complexity
O(m^3) – The dynamic programming table stores reachable tuples of (used_elements, carry, set_bits). Since used_elements <= m, carry <= m, and set_bits <= k <= m, the number of states stored simultaneously is bounded by O(m^3).

Edge Cases

Empty array or null input for the array or magical sequences
How to Handle:
Return zero immediately since no products can be formed.
Magical sequences contain indices that are out of bounds for the array
How to Handle:
Validate indices before access and ignore or treat missing elements as zero or one depending on sequence rules.
Very large intermediate products exceeding standard integer limits
How to Handle:
Apply modulo arithmetic using 10^9 + 7 at each multiplication step to prevent integer overflow.
Array elements containing negative numbers and zeros
How to Handle:
Ensure the multiplication logic correctly accounts for signs and zero products which zero out the sequence sum.
Maximum-sized inputs with a massive number of sequences
How to Handle:
Use an efficient linear scan and precomputed lookups to ensure the solution scales within acceptable time complexity.
Magical sequences that overlap and reference the exact same array elements multiple times
How to Handle:
Compute each sequence product independently and sum them up without deduplicating unless specified by the problem constraints.
Magical sequences containing zero elements
How to Handle:
Handle empty sequences by defining their product as one or zero based on mathematical convention for empty products.
Array values consisting entirely of ones or zeros
How to Handle:
Optimize the calculation by recognizing trivial products to avoid redundant arithmetic operations.
0/257 completed