Maximum XOR After Operations - Problem

You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).

Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.

Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,8]
Output: 11
💡 Note: We can achieve maximum XOR by applying operations strategically. The optimal value is the OR of all numbers: 3 | 2 | 8 = 11. This works because we can turn off any bits we don't want.
Example 2 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: With only one element, the maximum XOR is the element itself. No operations can increase the XOR value since we can only turn bits OFF.
Example 3 — Powers of Two
$ Input: nums = [1,2,4,8]
Output: 15
💡 Note: Each number has a different bit set. The OR of all gives 1|2|4|8 = 15 (binary 1111), which is also the maximum possible XOR we can achieve.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 108

Visualization

Tap to expand
Maximum XOR After Operations: [3, 2, 8]328001100101000Bit Positions:Bit 3: 0|0|1 = 1 ✓Bit 2: 0|0|0 = 0Bit 1: 1|1|0 = 1 ✓Bit 0: 1|0|0 = 1 ✓Operation: nums[i] & (nums[i] ^ x) can turn OFF any bitKey: We can eliminate unwanted bits from any positionMaximum XOR = 113 | 2 | 8 = 1011₂ = 11Simply OR all numbers to get maximum possible XOR
Understanding the Visualization
1
Input Array
Array of integers with their binary representations
2
Operation Analysis
nums[i] & (nums[i] ^ x) can turn any bit OFF
3
Maximum XOR
OR of all numbers gives maximum achievable XOR
Key Takeaway
🎯 Key Insight: Since the operation can only turn bits OFF, the maximum XOR equals the OR of all numbers
Asked in
Amazon 15 Microsoft 12 Google 8
12.3K Views
Medium Frequency
~15 min Avg. Time
456 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen