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

Maximum Xor Product

Difficulty: Medium


Problem Description

Given three integers a, b, and n, return the maximum value of (a XOR x) * (b XOR x) where 0 <= x < 2^n. Since the answer may be too large, return it modulo 10^9 + 7. Note that XOR is the bitwise XOR operation.


Key Insights

  • The XOR operation has properties that can be leveraged to maximize the product.
  • The maximum product occurs when the values of (a XOR x) and (b XOR x) are maximized.
  • The range of x can be represented with n bits, allowing exploration of all possible values using a bit manipulation approach.
  • The product can be computed efficiently by iterating through potential values of x and calculating the resulting products.

Space and Time Complexity

Time Complexity: O(2^n) in the worst case, but can be optimized. Space Complexity: O(1), as we only need a few variables to keep track of the maximum product.


Solution

To solve this problem, we can iterate over all possible values of x from 0 to 2^n - 1. For each value of x, we compute (a XOR x) and (b XOR x), then calculate the product. We keep track of the maximum product found during these iterations. The final result is returned modulo 10^9 + 7.


Code Solutions

def maxXorProduct(a, b, n):
    MOD = 10**9 + 7
    max_product = 0
    
    for x in range(1 << n):
        product = (a ^ x) * (b ^ x)
        max_product = max(max_product, product)
    
    return max_product % MOD
← Back to All Questions