Bird
Raised Fist0
Interview Prepchallenge-problemshardGoogleAmazon

Maximum XOR With Element From Array

Choose your preparation mode4 modes available
📋
Problem

Imagine you have a database of encrypted keys and want to find the best key to unlock a device by maximizing the XOR with a given query, but only among keys that meet certain constraints.

You are given an array nums of non-negative integers and an array queries where queries[i] = [x_i, m_i]. For each query i, find the maximum XOR value of x_i with any element in nums that is less than or equal to m_i. If no such element exists, return -1 for that query. Return an array answer where answer[i] is the answer to the i-th query.

1 ≤ nums.length, queries.length ≤ 10^50 ≤ nums[i], x_i, m_i ≤ 10^9
Edge cases: No elements in nums are ≤ m_i → output -1All nums elements are zero → XOR results depend only on x_iQueries with x_i = 0 → max XOR is max element ≤ m_i
</>
IDE
def maximizeXor(nums: list[int], queries: list[list[int]]) -> list[int]:public int[] maximizeXor(int[] nums, int[][] queries)vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries)function maximizeXor(nums, queries)
def maximizeXor(nums, queries):
    # Write your solution here
    pass
class Solution {
    public int[] maximizeXor(int[] nums, int[][] queries) {
        // Write your solution here
        return new int[queries.length];
    }
}
#include <vector>
using namespace std;

vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {
    // Write your solution here
    return vector<int>(queries.size(), -1);
}
function maximizeXor(nums, queries) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Returning max nums ≤ m_i instead of max XORConfusing max element filtering with max XOR calculation.✅ Compute max XOR by iterating over all nums ≤ m_i and taking max(x_i ^ num).
Wrong: Returning -1 incorrectly when nums is not emptyIncorrect filtering or off-by-one error in checking nums ≤ m_i.✅ Use ≤ operator when filtering nums by m_i, not <.
Wrong: Failing to handle empty nums array, returning non -1 valuesNot checking for empty nums before processing queries.✅ Return -1 for all queries if nums is empty.
Wrong: Greedy approach picking largest nums ≤ m_i without XOR checkAssuming largest nums element gives max XOR without verifying.✅ Check XOR with all eligible nums to find max XOR.
Wrong: TLE on large inputsUsing brute force O(n*q) approach.✅ Implement offline queries with sorting and bitwise trie for O((n+q)*log(maxNum)) complexity.
✓
Test Cases
t1_01basic
Input{"nums":[0,1,2,3,4],"queries":[[3,1],[1,3],[5,6]]}
Expected[3,3,7]

For query [3,1], elements ≤1 are [0,1], max XOR with 3 is 3 (3^0=3, 3^1=2). For [1,3], elements ≤3 are [0,1,2,3], max XOR with 1 is 3 (1^2=3). For [5,6], elements ≤6 are all nums, max XOR with 5 is 7 (5^2=7).

t1_02basic
Input{"nums":[5,8,10,12],"queries":[[7,10],[0,5],[15,12]]}
Expected[15,5,10]

Query [7,10]: nums ≤10 are [5,8,10], max XOR with 7 is 15 (7^8=15). Query [0,5]: nums ≤5 is [5], max XOR with 0 is 5 (0^5=5). Query [15,12]: nums ≤12 are [5,8,10,12], max XOR with 15 is 15 (15^0=15 if 0 existed, but here max is 15^10=5, 15^12=3, 15^8=7, 15^5=10; max is 15^10=5? Actually max is 15^10=5, but 15^5=10, 15^8=7, 15^12=3, so max is 15^5=10. Recompute carefully: 15^5=10, 15^8=7, 15^10=5, 15^12=3, max is 10. So expected is [15,5,10].

t2_01edge
Input{"nums":[],"queries":[[1,1],[0,0]]}
Expected[-1,-1]

Empty nums array means no elements to XOR with; all queries return -1.

t2_02edge
Input{"nums":[0],"queries":[[0,0],[1,0],[2,1]]}
Expected[0,1,2]

Only nums element is 0. For queries with m_i ≥ 0, max XOR is x_i ^ 0 = x_i. For query [2,1], nums ≤1 is [0], max XOR is 2.

t2_03edge
Input{"nums":[1,2,3],"queries":[[2,2],[3,3],[0,0]]}
Expected[3,2,-1]

Query [2,2]: nums ≤2 are [1,2], max XOR with 2 is max(2^1=3,2^2=0)=3. Query [3,3]: nums ≤3 are [1,2,3], max XOR with 3 is max(3^1=2,3^2=1,3^3=0)=2. Query [0,0]: nums ≤0 is empty, return -1.

t3_01corner
Input{"nums":[1,2,4,8],"queries":[[7,8],[7,4]]}
Expected[15,6]

Query [7,8]: nums ≤8 are [1,2,4,8], max XOR with 7 is 15 (7^8=15). Query [7,4]: nums ≤4 are [1,2,4], max XOR with 7 is 7 (7^0=7 if 0 existed, but here max is 7^4=3, 7^2=5, 7^1=6; max is 7^1=6? Actually 7^4=3, 7^2=5, 7^1=6, max is 7^1=6. So expected is [15,6].

t3_02corner
Input{"nums":[2,2,2],"queries":[[3,2],[1,2]]}
Expected[1,3]

All nums are identical 2. For query [3,2], max XOR is 3^2=1. For [1,2], max XOR is 1^2=3.

t3_03corner
Input{"nums":[0,1,2,3,4],"queries":[[0,0],[0,1],[0,4]]}
Expected[0,1,4]

Queries with x_i=0: max XOR is max nums ≤ m_i. For m_i=0 max is 0, for m_i=1 max is 1, for m_i=4 max is 4.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

Test with n=100000 nums and queries at max constraints to ensure O((n+q)*log(maxNum)) solution runs within 2 seconds.

Practice

(1/5)
1. Given the following code snippet implementing the optimal approach to find the median of two sorted arrays, what is the returned median for input nums1 = [1, 3], nums2 = [2]?
easy
A. 1.5
B. 2.5
C. 2.0
D. 3.0

Solution

  1. Step 1: Trace initial variables

    nums1=[1,3], nums2=[2], m=2, n=1, swap occurs so nums1=[2], nums2=[1,3], m=1, n=2, half_len=2.
  2. Step 2: First iteration of binary search

    low=0, high=1, i=0, j=2-0=2; max_left_nums1=-inf, min_right_nums1=2; max_left_nums2=nums2[1]=3, min_right_nums2=inf. Condition fails, low updated to i+1=1.
  3. Step 3: Second iteration

    i=1, j=1; max_left_nums1=2, min_right_nums1=inf; max_left_nums2=nums2[0]=1, min_right_nums2=nums2[1]=3. Condition satisfied.
  4. Step 4: Calculate median

    Total length is odd (3), median is max(max_left_nums1, max_left_nums2) = max(2,1) = 2.0.
  5. Final Answer:

    Option C -> Option C
  6. Quick Check:

    Median of [1,2,3] is 2.0 [OK]
Hint: Swap arrays to binary search smaller one; median is 2.0 [OK]
Common Mistakes:
  • Not swapping arrays leads to wrong partition
  • Off-by-one in i or j calculation
  • Confusing odd/even median calculation
2. You need to place n queens on an nxn chessboard so that no two queens threaten each other. Which algorithmic approach guarantees finding all valid configurations efficiently by pruning invalid partial solutions early?
easy
A. Backtracking that tries all column positions per row and prunes invalid placements using sets or bitmasks
B. Greedy algorithm that places queens row by row choosing the first safe column
C. Dynamic programming that stores subproblems of partial queen placements by rows and columns
D. Divide and conquer by splitting the board into smaller sub-boards and solving independently

Solution

  1. Step 1: Understand problem constraints

    The problem requires placing queens so none attack each other, which involves checking columns and diagonals.
  2. Step 2: Identify approach that prunes invalid states

    Backtracking tries all placements but prunes invalid ones early using sets or bitmasks, guaranteeing all solutions without brute force.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Backtracking with pruning is standard for N-Queens [OK]
Hint: Backtracking prunes invalid queen placements early [OK]
Common Mistakes:
  • Thinking greedy placement always works
  • Confusing DP with backtracking
  • Assuming independent subproblems in divide and conquer
3. You are given k sorted lists of integers. Your task is to find the smallest range that includes at least one number from each of the k lists. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Use a greedy approach that always picks the smallest current element and expands the range until all lists are covered.
B. Merge all lists into one sorted array with list indices, then use a two-pointer sliding window to find the minimal range covering all lists.
C. Apply dynamic programming to track the minimal range for subsets of lists incrementally.
D. Enumerate all possible combinations of elements from each list and select the combination with the smallest range.

Solution

  1. Step 1: Understand problem constraints

    The problem requires a range covering at least one element from each list, which suggests tracking coverage across lists.
  2. Step 2: Evaluate approaches

    Greedy alone fails because it doesn't guarantee minimal range; DP is not suitable due to combinatorial explosion; brute force enumerates all combos but is inefficient. Merging all lists and using two pointers efficiently tracks coverage and minimal range.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Two-pointer on merged array is known optimal [OK]
Hint: Two pointers on merged array track coverage efficiently [OK]
Common Mistakes:
  • Thinking greedy alone suffices
  • Assuming DP applies directly
  • Using brute force for large inputs
4. What is the time complexity of the space-optimized bottom-up dynamic programming solution for the edit distance problem, where the input strings have lengths m and n respectively?
medium
A. O(m * n)
B. O(m + n)
C. O(m * n * min(m, n))
D. O(3^(m + n))

Solution

  1. Step 1: Identify nested loops over m and n

    The algorithm iterates over all pairs of indices (i, j) with i in [0, m) and j in [0, n), performing constant work per pair.
  2. Step 2: Confirm no extra multiplicative factors

    Each cell computation is O(1), so total time is O(m * n). The recursion stack or auxiliary space does not affect time complexity.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    DP table size m*n and constant work per cell [OK]
Hint: DP over m*n cells -> O(m*n) time [OK]
Common Mistakes:
  • Confusing recursion stack space with time
  • Assuming exponential due to recursion without memoization
5. Suppose the problem is modified so that digits can be reused any number of times to form expressions (e.g., "1+1+2+3" from "123"). Which modification to the backtracking algorithm correctly handles this variant without infinite loops?
hard
A. Remove the index increment in recursive calls to allow reuse of digits indefinitely
B. Add a visited set to track used indices and prevent reusing digits more than once
C. Allow recursive calls to reuse digits by not incrementing index, but limit expression length to avoid infinite recursion
D. Modify recursion to restart from index 0 after each operator insertion, but track expression length to prevent infinite loops

Solution

  1. Step 1: Understand reuse implications

    Allowing reuse means digits can be chosen multiple times, so index must be reset or not incremented to allow reuse.
  2. Step 2: Prevent infinite recursion

    Resetting index to 0 after operator insertion allows reuse, but expression length must be tracked and limited to avoid infinite loops.
  3. Step 3: Evaluate options

    Modify recursion to restart from index 0 after each operator insertion, but track expression length to prevent infinite loops correctly resets index and tracks length. Remove the index increment in recursive calls to allow reuse of digits indefinitely causes infinite loops by never incrementing index. Add a visited set to track used indices and prevent reusing digits more than once forbids reuse. Allow recursive calls to reuse digits by not incrementing index, but limit expression length to avoid infinite recursion risks infinite recursion without explicit length limit.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Reset index with length limit prevents infinite recursion while allowing reuse [OK]
Hint: Reuse requires index reset plus recursion depth control [OK]
Common Mistakes:
  • Not limiting recursion depth causing infinite loops
  • Using visited set forbidding reuse
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard