#2317

Maximum XOR After Operations

Medium
ArrayMathBit ManipulationBit ManipulationGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we can unset any bit in nums[i] by choosing appropriate values of x. This allows us to focus on maximizing the bits that can remain set in the final XOR result.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to store the maximum XOR result.
  2. 2Step 2: Iterate through each number in the array and calculate the maximum possible XOR by considering the bits that can be set.
  3. 3Step 3: Use a bitmask to keep track of the bits that can be set based on the numbers in the array.
  4. 4Step 4: For each bit position, check if it can be set in the final result by ensuring at least one number can contribute that bit.
solution.py14 lines
1# Full working Python code
2
3def maxXOR(nums):
4    max_xor = 0
5    for i in range(31, -1, -1):
6        temp = max_xor | (1 << i)
7        found = False
8        for num in nums:
9            if (num & temp) == temp:
10                found = True
11                break
12        if found:
13            max_xor = temp
14    return max_xor

Complexity note: This complexity is linear because we only iterate through the array a fixed number of times (once for each bit position) rather than checking every possible combination.

  • 1The ability to unset bits allows for flexibility in maximizing the XOR result.
  • 2Focusing on the highest bits first helps in constructing the maximum possible XOR efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.