Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit.
Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit.
def max_xor(a):
ans = mask = 0
for b in range(5, -1, -1):
mask |= 1 << b
prefixes = {x & mask for x in a}
cand = ans | (1 << b)
if any(cand ^ p in prefixes for p in prefixes): ans = cand
return ans
print(max_xor([3, 10, 5, 25, 2, 8]))What is printed?- A. 31
- B. 27
- C. 25
- D. 28
Correct answer: D. 28
Build the answer from the top bit: try setting the next bit and check, using the property a ^ b = c ⟺ a ^ c = b, whether two prefixes achieve it. 5 ^ 25 = 00101 ^ 11001 = 11100 = 28. The same idea with a binary trie is O(n · bits).
More Coding Interview Problems questions
- Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range. python…
- Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7. java static long ways3(int n) { long MOD =…
- Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost. python def…
- Problem: Count palindromic substrings (each occurrence counts separately). python def countpal(s): n, c = len(s), 0 for center in range(2…
- Problem: Find the length of the longest arithmetic subsequence. python def longestap(a): dp = [{} for in a]; best = 1 for i in…
- Problem: Length of the longest strictly increasing subsequence with the O(n²) DP. cpp int lis(vector<int>& a) { vector<int> dp(a.size()…