← Questions
Maximum XOR product of two numbers under one mask
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Given integers a, b and n, choose x with 0 <= x < 2^n to maximize (a XOR x) * (b XOR x). Return the maximum modulo 10^9 + 7. Compare candidates by their true product, not by the product after the modulo.
Interface
Unless you agree on a different interface with the interviewer, assume:
maximum_xor_product(a: int, b: int, n: int) -> int
Example
maximum_xor_product(12, 5, 4) -> 98 # x = 2: 14 * 7
maximum_xor_product(6, 7, 5) -> 930 # x = 25: 31 * 30
maximum_xor_product(1, 6, 3) -> 12 # x = 5: 4 * 3
Constraints
0 <= a, b < 2^500 <= n <= 50
Clarifying questions
- Is the modulo applied only to the final answer?
- Can
nbe 0 (thenxmust be 0)? - Can
nbe smaller than the bit length ofaorb? (Yes: bits abovenare fixed.)
What a strong answer covers
- Bits at positions
>= ncannot change; keep them as they are inaandb. - For each bit below
nwhereaandbagree, set it to 1 in both results: it raises both factors. - Where they differ, exactly one result gets the bit, so the sum is fixed. A product with a fixed sum is largest when the factors are as close as possible: go from the high bit down and give each differing bit to the factor that is currently smaller.
- The fixed bits above
ncount when deciding which factor is smaller; once one factor pulls ahead, every later differing bit goes to the other. - O(n) time, O(1) space; Python integers or 64-bit math before the final modulo.
- A brute-force check over all
xfor smallnas a test oracle.
Follow-ups
- Return the
xthat achieves the maximum (smallest one on ties). - Maximize
(a XOR x) + (b XOR x)instead; what changes? - Three numbers
a,b,cwith the samex.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
