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 implementing the optimal approach to find the median of two sorted arrays, what is the returned median for input nums1 = [1, 3], nums2 = [2]?
Total length is odd (3), median is max(max_left_nums1, max_left_nums2) = max(2,1) = 2.0.
Final Answer:
Option C -> Option C
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
Step 1: Understand problem constraints
The problem requires placing queens so none attack each other, which involves checking columns and diagonals.
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.
Final Answer:
Option A -> Option A
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
Step 1: Understand problem constraints
The problem requires a range covering at least one element from each list, which suggests tracking coverage across lists.
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.
Final Answer:
Option B -> Option B
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
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.
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.
Final Answer:
Option A -> Option A
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
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.
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.
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.
Final Answer:
Option D -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.