MediumNo. 2939

Maximum Xor Product — LeetCode 2939 Python Solution

Topics
Greedy, Bit Manipulation, Math
Reading time
3 min

The problem

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.

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.

Python solution

PythonSolution
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

Time
O(n)where n is the integer given in the problem
Space · auxiliary
O(1)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2939. Maximum Xor Product is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0670Maximum SwapMedium
0738Monotone Increasing DigitsMedium
0861Score After Flipping MatrixMedium
0910Smallest Range IIMedium
0976Largest Perimeter TriangleEasy
0991Broken CalculatorMedium

Frequently asked questions

How hard is LeetCode 2939. Maximum Xor Product?

LeetCode 2939. Maximum Xor Product is rated Medium on LeetCode.

What is the time complexity of LeetCode 2939. Maximum Xor Product?

The Python solution on this page runs in O(n), where n is the integer given in the problem.

What is the space complexity of LeetCode 2939. Maximum Xor Product?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2939. Maximum Xor Product cover?

LeetCode 2939. Maximum Xor Product is tagged Greedy, Bit Manipulation and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.