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,4,6]
Output: 7
💡 Note: Operations can only clear bits. The bitwise OR 3|2|4|6 = 011|010|100|110 = 111 = 7 gives maximum XOR.
Example 2 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: With only one element, no XOR operation is needed. The maximum is the element itself: 1.
Example 3 — Powers of 2
$ Input: nums = [1,2,4,8]
Output: 15
💡 Note: OR of powers of 2: 0001|0010|0100|1000 = 1111 = 15. Each bit position has exactly one 1.

Constraints

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

Visualization

Tap to expand
INPUTALGORITHMRESULT3246011010100110nums = [3,2,4,6]1Bitwise OR Operation2011 | 010 = 0113011 | 100 = 1114111 | 110 = 111Keep all possible 1-bits7Maximum XORBinary: 111Key Insight:The operation can only clear bits, never set new ones.Maximum XOR = Bitwise OR of all elements.TutorialsPoint - Maximum XOR After Operations | Bit Manipulation
Asked in
Google 25 Facebook 18 Amazon 15
28.4K Views
Medium Frequency
~10 min Avg. Time
892 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