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 for finding concatenated words, what is the value of memo after calling dfs('catsdog', 0) on the input ['cat', 'cats', 'dog', 'catsdog']?
easy
A. {0: True, 3: True, 4: True, 7: True}
B. {0: True, 3: True, 4: False}
C. {0: True, 3: False, 4: True}
D. {0: False, 3: True, 4: True}

Solution

  1. Step 1: Trace dfs('catsdog', 0) calls and memo updates

    Start=0: check prefixes 'cat'(0-3), 'cats'(0-4). 'cat' leads to dfs(3), 'cats' leads to dfs(4).
  2. Step 2: Evaluate dfs(3) and dfs(4)

    dfs(3) checks 'sdog' prefix - no match, returns False; dfs(4) checks 'dog' prefix - matches 'dog', dfs(7) returns True; memo[4]=True, memo[3]=False, memo[0]=True.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Memo correctly records True at 0 and 4, False at 3 [OK]
Hint: Memo stores start indices where suffix can form concatenation [OK]
Common Mistakes:
  • Confusing indices or forgetting to memoize False results
2. You are given a list of words and need to find the longest word such that every prefix of the word is also in the list. Which approach guarantees an optimal solution for this problem?
easy
A. Sort the words by length and lex order, then check prefixes using a hash set.
B. Apply a greedy approach by always choosing the lexicographically smallest prefix at each step.
C. Use dynamic programming to build the longest word by extending smaller valid words.
D. Build a trie from the words and perform a BFS traversal to find the longest valid word.

Solution

  1. Step 1: Understand the prefix condition

    The problem requires that every prefix of the candidate word must be present in the list, which naturally fits a trie structure where each node represents a prefix.
  2. Step 2: Why BFS on trie works best

    BFS traversal on the trie allows level-by-level exploration, ensuring that only nodes representing complete words are considered, thus guaranteeing the longest word with all prefixes present is found efficiently.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Trie + BFS directly encodes prefix checks and finds longest word [OK]
Hint: Trie BFS ensures prefix validity and longest word [OK]
Common Mistakes:
  • Assuming greedy lex order always works
  • Using DP without prefix structure
  • Checking prefixes inefficiently without trie
3. What is the time complexity of the optimal trie + DFS approach to find all index pairs of substrings matching words, where n is the length of the text and m is the maximum length of any word in the list?
medium
A. O(n * n * m) because DFS explores all substrings up to length m from each index
B. O(w * m + n * m) where w is number of words, for trie build and DFS search
C. O(n * log m) because trie traversal is logarithmic in word length
D. O(n * m) because DFS from each index explores at most m characters in the trie

Solution

  1. Step 1: Analyze DFS calls per index

    From each of the n indices, DFS explores at most m characters (max word length) in the trie, pruning early if no child exists.
  2. Step 2: Combine trie build and DFS search

    Trie build is O(w * m), but dominant search time is O(n * m). The question asks for search complexity, which is O(n * m).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DFS prunes search to max word length per start index [OK]
Hint: DFS depth limited by max word length m [OK]
Common Mistakes:
  • Assuming DFS explores all substrings (O(n^2))
  • Confusing trie build cost with search cost
4. What is the time complexity of the optimal trie + BFS approach for finding the longest word in a dictionary with n words, each of average length m?
medium
A. O(n * m + n * 26) because building trie takes O(n*m) and BFS visits each node once
B. O(n * m * 26) since BFS explores all children for each character
C. O(n * m^2) due to checking all prefixes for each word
D. O(n * m log n) due to sorting children at each node during BFS

Solution

  1. Step 1: Analyze trie construction

    Inserting n words of length m takes O(n * m) time as each character is processed once.
  2. Step 2: Analyze BFS traversal

    BFS visits each node once; each node has up to 26 children, so total BFS cost is O(n * 26) which is O(n).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Trie build + BFS traversal sum to O(n*m + n*26) [OK]
Hint: Trie build O(n*m), BFS O(n*26) combined [OK]
Common Mistakes:
  • Confusing BFS cost as O(n*m*26)
  • Forgetting BFS visits each node once
  • Assuming sorting children adds log factor per node
5. Suppose the problem changes: you want to find the maximum XOR of two numbers in an array, but now numbers can be negative 32-bit integers. Which modification to the bitwise trie approach is necessary to handle negative numbers correctly?
hard
A. Use two's complement 32-bit representation and treat bits as unsigned during trie insertion and traversal
B. Ignore sign bit and only build trie from absolute values of numbers
C. Use 64-bit representation to store numbers in trie to avoid sign issues
D. Preprocess numbers by adding a large constant to make all numbers positive before building trie

Solution

  1. Step 1: Understand representation of negative numbers

    Negative integers in 32-bit are stored in two's complement form, which can be treated as unsigned bit patterns for trie operations.
  2. Step 2: Modify trie insertion and traversal

    Insert and traverse bits as unsigned 32-bit integers, including the sign bit, to correctly handle negative numbers.
  3. Step 3: Avoid incorrect approaches

    Using 64-bit or adding constants changes problem semantics; ignoring sign bit loses information.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Two's complement allows uniform bitwise trie handling of negative numbers [OK]
Hint: Two's complement bits can be treated as unsigned [OK]
Common Mistakes:
  • Ignoring sign bit or converting to absolute values
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