Leetcode #2939: Maximum Xor Product
In this guide, we solve Leetcode #2939 Maximum Xor Product in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given three integers a, b, and n, return the maximum value of (a XOR x) * (b XOR x) where 0 <= x < 2n. Since the answer may be too large, return it modulo 109 + 7.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Greedy, Bit Manipulation, Math
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: a = 12, b = 5, n = 4
Output: 98
Explanation: For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98.
It can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.
Python Solution
class Solution:
def maximumXorProduct(self, a: int, b: int, n: int) -> int:
mod = 10**9 + 7
ax, bx = (a >> n) << n, (b >> n) << n
for i in range(n - 1, -1, -1):
x = a >> i & 1
y = b >> i & 1
if x == y:
ax |= 1 << i
bx |= 1 << i
elif ax > bx:
bx |= 1 << i
else:
ax |= 1 << i
return ax * bx % mod
Complexity
The time complexity is , where is the integer given in the problem. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.