Maximum Xor Product — LeetCode 2939 Python Solution

MediumGreedyBit ManipulationMath
Problem
#2939
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

Python
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

MeasureComplexity
TimeO(n), where n is the integer given in the problem
SpaceO(1) auxiliary

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

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.

Get Stealth Interview