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

Leetcode #1829: Maximum XOR for Each Query

In this guide, we solve Leetcode #1829 Maximum XOR for Each Query 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 a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times: Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ...

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Bit Manipulation, Array, Prefix Sum

Intuition

Range queries become simple once we precompute cumulative sums.

We can transform subarray conditions into prefix comparisons.

Approach

Compute prefix sums and use a map to find matching prefixes.

This avoids nested loops while keeping the logic clear.

Steps:

  • Compute prefix sums.
  • Use a map to find valid ranges.
  • Update the answer.

Example

Input: nums = [0,1,1,3], maximumBit = 2 Output: [0,3,2,3] Explanation: The queries are answered as follows: 1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3. 2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3. 3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3. 4th query: nums = [0], k = 3 since 0 XOR 3 = 3.

Python Solution

class Solution: def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]: ans = [] xs = reduce(xor, nums) for x in nums[::-1]: k = 0 for i in range(maximumBit - 1, -1, -1): if (xs >> i & 1) == 0: k |= 1 << i ans.append(k) xs ^= x return ans

Complexity

The time complexity is O(n×m)O(n \times m)O(n×m), where nnn and mmm are the values of the array nums and maximumBit respectively. The space complexity is O(1)O(1)O(1).

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