Skip to main content
Back to problems
#1707
Hard Algorithms

Maximum xor with an element from array

Array Bit Manipulation Trie
57.6% acceptance
Feb 25, 2026
1403
40
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi]. The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1. Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn maximize_xor(mut nums: Vec<i32>, queries: Vec<Vec<i32>>) -> Vec<i32> {
    nums.sort_unstable();
    let q_len = queries.len();
    let mut idx: Vec<usize> = (0..q_len).collect();
    idx.sort_unstable_by_key(|&i| queries[i][1]);
    let max_nodes = (nums.len() + q_len) * 32 + 10;
    let mut trie = vec![-1i32; max_nodes * 2];
    let mut node_count = 1usize;
    let mut ni = 0usize;
    let mut ans = vec![0i32; q_len];
    for qi in idx {
      let x = queries[qi][0];
      let m = queries[qi][1];
      while ni < nums.len() && nums[ni] <= m {
        let mut cur = 0usize;
        for bit in (0..30).rev() {
          let b = ((nums[ni] >> bit) & 1) as usize;
          if trie[cur * 2 + b] == -1 {
            trie[cur * 2 + b] = node_count as i32;
            node_count += 1;
          }
          cur = trie[cur * 2 + b] as usize;
        }
        ni += 1;
      }
      if ni == 0 {
        ans[qi] = -1;
      } else {
        let mut cur = 0usize;
        let mut result = 0i32;
        let mut valid = true;
        for bit in (0..30).rev() {
          let b = ((x >> bit) & 1) as usize;
          let want = 1 - b;
          if trie[cur * 2 + want] != -1 {
            result |= 1 << bit;
            cur = trie[cur * 2 + want] as usize;
          } else if trie[cur * 2 + b] != -1 {
            cur = trie[cur * 2 + b] as usize;
          } else {
            valid = false;
            break;
          }
        }
        ans[qi] = if valid { result } else { -1 };
      }
    }
    ans
  }
}