We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Non-Zero Product of the Array Elements

Number: 2100

Difficulty: Medium

Paid? No

Companies: Amazon, PayPal


Problem Description

Given a positive integer p, consider an array nums that consists of the integers in the inclusive range [1, 2^p - 1] (each represented in binary). You are allowed to perform any number of operations where you choose two elements x and y from nums, then swap a corresponding bit (i.e. same position) between them. The goal is to minimize the non-zero product of the array elements after performing these operations any number of times. Return the result modulo 10^9 + 7.


Key Insights

  • The maximum value in the array is M = 2^p - 1.
  • The minimum non-zero product is achieved by pairing M - 1 (which is 2^p - 2) as many times as possible and then multiplying by M once.
  • The number of times M - 1 is used is 2^(p-1) - 1.
  • The answer can be computed as: ans = M * (M - 1)^(2^(p-1) - 1) modulo 10^9 + 7.
  • Fast exponentiation is essential to handle the large exponent efficiently.

Space and Time Complexity

Time Complexity: O(log(2^(p-1))) which is O(p); however, due to the use of fast exponentiation, it is efficient for p up to 60.
Space Complexity: O(1)


Solution

We start by noting that when p equals 1, the only number in the array is 1, so the answer is 1. For p > 1, the highest value in the array is M = 2^p - 1.
The optimal strategy involves maximizing the use of the number M - 1 (which is 2^p - 2) as factors in the product. Precisely, the optimal product is given by multiplying M exactly once and (M - 1) repeatedly for (2^(p-1) - 1) times.
Thus, the answer is:
  ans = M * (M - 1)^(2^(p-1) - 1) modulo 10^9 + 7
We use modular exponentiation to compute the large exponent in an efficient manner.


Code Solutions

# Python solution with line-by-line comments

MOD = 10**9 + 7

def minNonZeroProduct(p):
    # Base case: if p equals 1, return 1 as the only possible product
    if p == 1:
        return 1
    
    # Calculate the maximum value in the array, M = 2^p - 1
    max_val = (1 << p) - 1
    
    # Calculate the exponent which is (2^(p-1) - 1)
    exponent = (1 << (p - 1)) - 1
    
    # Calculate (max_val - 1) raised to the power 'exponent' modulo MOD using pow with three arguments for fast mod exponentiation
    product = pow(max_val - 1, exponent, MOD)
    
    # Multiply by max_val and take modulo MOD as final answer
    result = (max_val * product) % MOD
    return result

# Example usage:
print(minNonZeroProduct(3))  # Expected output: 1512
← Back to All Questions