#2939

Maximum Xor Product

Medium
MathGreedyBit ManipulationBit ManipulationGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach leverages bit manipulation. By analyzing the bits of a and b, we can determine the best x that maximizes the product without needing to check every possible x. We focus on setting bits in x such that (a XOR x) and (b XOR x) yield the highest possible values.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize max_product to 0.
  2. 2Step 2: Iterate over each bit position from the most significant to the least significant (up to n bits).
  3. 3Step 3: For each bit, determine if setting that bit in x can maximize the product based on the current bits of a and b.
  4. 4Step 4: Calculate the potential maximum product based on the chosen bits for x.
  5. 5Step 5: Return the maximum product modulo (10^9 + 7).
solution.py10 lines
1# Full working Python code
2
3def max_xor_product(a, b, n):
4    max_product = 0
5    for i in range(n - 1, -1, -1):
6        x = (1 << i)
7        product1 = (a ^ x) * (b ^ x)
8        product2 = (a ^ 0) * (b ^ 0)
9        max_product = max(max_product, product1, product2)
10    return max_product % (10**9 + 7)

Complexity note: This complexity is efficient because we only iterate through the bits of n, making it linear with respect to the number of bits rather than the number of possible x values.

  • 1The XOR operation can be manipulated to maximize individual bits, allowing for strategic choices in x.
  • 2Understanding how to set bits in x based on the bits of a and b can lead to significant optimizations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.