Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1707: Maximum XOR With an Element From Array

In this guide, we solve Leetcode #1707 Maximum XOR With an Element From Array in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Bit Manipulation, Trie, Array

Intuition

Prefix queries are most efficient with a trie.

Each character transitions to the next node in the tree.

Approach

Insert words into the trie and traverse by characters for queries.

Track terminal markers to distinguish full words from prefixes.

Steps:

  • Build the trie.
  • Traverse for each query.
  • Return matches or validations.

Example

Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]] Output: [3,3,7] Explanation: 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3. 2) 1 XOR 2 = 3. 3) 5 XOR 2 = 7.

Python Solution

class Trie: __slots__ = ["children"] def __init__(self): self.children = [None] * 2 def insert(self, x: int): node = self for i in range(30, -1, -1): v = x >> i & 1 if node.children[v] is None: node.children[v] = Trie() node = node.children[v] def search(self, x: int) -> int: node = self ans = 0 for i in range(30, -1, -1): v = x >> i & 1 if node.children[v ^ 1]: ans |= 1 << i node = node.children[v ^ 1] elif node.children[v]: node = node.children[v] else: return -1 return ans class Solution: def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: trie = Trie() nums.sort() j, n = 0, len(queries) ans = [-1] * n for i, (x, m) in sorted(zip(range(n), queries), key=lambda x: x[1][1]): while j < len(nums) and nums[j] <= m: trie.insert(nums[j]) j += 1 ans[i] = trie.search(x) return ans

Complexity

The time complexity is O(m×log⁡m+n×(log⁡n+log⁡M))O(m \times \log m + n \times (\log n + \log M))O(m×logm+n×(logn+logM)), and the space complexity is O(n×log⁡M)O(n \times \log M)O(n×logM). The space complexity is O(n×log⁡M)O(n \times \log M)O(n×logM).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy