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.
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
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
Focus on handling empty and minimal inputs correctly before tackling edge cases.
Think about common algorithmic traps like greedy selection and identical elements.
Prepare to optimize your solution using offline queries and bitwise trie data structures.
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).
💡 Consider each query independently and find nums elements ≤ m_i.
💡 Use brute force XOR with all eligible nums elements to find max.
💡 For each query, max XOR = max(x_i ^ num) for num ≤ m_i; if none, return -1.
Why it failed: Incorrect output means failure to filter nums by m_i or incorrect XOR max calculation. Fix by ensuring only nums ≤ m_i are considered and max XOR is computed correctly.
✓ Correctly filters nums by m_i and computes max XOR for each query.
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].
💡 Check filtering nums by m_i for each query.
💡 Calculate XOR of x_i with each eligible num and track max.
💡 Remember XOR is bitwise; verify max XOR by comparing all candidates.
Why it failed: Wrong max XOR means incorrect filtering or XOR calculation. Fix by iterating over nums ≤ m_i and updating max XOR properly.
✓ Correctly computes max XOR for all queries with proper filtering.
t2_01edge
Input{"nums":[],"queries":[[1,1],[0,0]]}
Expected[-1,-1]
⏱ Performance - must finish in 2000ms
Empty nums array means no elements to XOR with; all queries return -1.
💡 Consider what happens if nums is empty.
💡 No elements ≤ m_i means answer is always -1.
💡 Return -1 for every query if nums is empty.
Why it failed: Returning values other than -1 means failure to handle empty nums. Fix by checking if nums is empty before processing queries.
✓ Correctly returns -1 for all queries when nums is empty.
t2_02edge
Input{"nums":[0],"queries":[[0,0],[1,0],[2,1]]}
Expected[0,1,2]
⏱ Performance - must finish in 2000ms
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.
💡 Test single element nums array.
💡 XOR with zero returns the other number unchanged.
💡 Ensure filtering by m_i includes the single element if eligible.
Why it failed: Incorrect output means failure to handle single element or filtering by m_i. Fix by including single element if ≤ m_i and XOR correctly.
✓ Correctly handles single element nums and filtering.
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.
💡 Test exact boundary condition where nums elements equal m_i.
💡 Check filtering includes elements equal to m_i, not just less than.
💡 Verify max XOR calculation among filtered elements.
Why it failed: Failing to include nums equal to m_i causes wrong output. Fix by using ≤ (less or equal) condition in filtering.
✓ Correctly includes nums equal to m_i and computes max XOR.
t3_01corner
Input{"nums":[1,2,4,8],"queries":[[7,8],[7,4]]}
Expected[15,6]
⏱ Performance - must finish in 2000ms
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].
💡 Beware greedy approaches that pick largest nums ≤ m_i without checking XOR.
💡 Try all eligible nums to find max XOR, not just max nums.
💡 Check all nums ≤ m_i for max XOR, not just the largest.
Why it failed: Greedy bug: picking largest nums ≤ m_i instead of max XOR. Fix by checking XOR with all eligible nums.
✓ Correctly computes max XOR by checking all eligible nums.
t3_02corner
Input{"nums":[2,2,2],"queries":[[3,2],[1,2]]}
Expected[1,3]
⏱ Performance - must finish in 2000ms
All nums are identical 2. For query [3,2], max XOR is 3^2=1. For [1,2], max XOR is 1^2=3.
💡 Check handling of all identical nums elements.
💡 XOR with identical elements can still produce different results depending on x_i.
💡 Do not assume all results are the same if nums elements are identical.
Why it failed: Assuming identical nums produce identical XOR results causes wrong output. Fix by computing XOR with x_i for each query.
✓ Correctly handles identical nums and computes XOR per query.
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.
💡 Test queries where x_i=0 to verify max XOR equals max nums ≤ m_i.
💡 Check filtering and max selection logic carefully.
💡 Return max nums ≤ m_i when x_i=0, else max XOR with x_i.
Why it failed: Failing to handle x_i=0 queries correctly causes wrong output. Fix by returning max nums ≤ m_i when x_i=0.
✓ Correctly handles x_i=0 queries by returning max nums ≤ m_i.
t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this input"}
Expectednull
⏱ 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.
💡 Brute force O(n*q) will time out; use offline queries and bitwise trie.
💡 Sort nums and queries by m_i and insert nums into trie incrementally.
💡 Use bitwise trie to find max XOR efficiently for each query.
Why it failed: TLE due to O(n*q) brute force approach. Fix by implementing offline queries with sorting and bitwise trie for O((n+q)*log(maxNum)) complexity.
✓ Efficient solution runs within time limit using offline queries and bitwise trie.
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
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).
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
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.
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.
Final Answer:
Option D -> Option D
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
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.
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).
Final Answer:
Option D -> Option D
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
Step 1: Analyze trie construction
Inserting n words of length m takes O(n * m) time as each character is processed once.
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).
Final Answer:
Option A -> Option A
Quick Check:
Trie build + BFS traversal sum to O(n*m + n*26) [OK]
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
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.
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.
Step 3: Avoid incorrect approaches
Using 64-bit or adding constants changes problem semantics; ignoring sign bit loses information.