Maximum XOR After Operations - Problem
Maximum XOR After Operations

You have a magical array of integers where you can perform special bitwise transformations! Given a 0-indexed integer array nums, you can repeatedly apply the following operation:

๐Ÿ“ Operation: Select any non-negative integer x and any index i, then transform nums[i] to nums[i] AND (nums[i] XOR x)

๐ŸŽฏ Goal: Find the maximum possible XOR of all elements in the array after applying this operation any number of times.

Key Insight: This operation can only turn bits from 1 to 0, never from 0 to 1. So for maximum XOR, we want to keep as many different bit positions set across all numbers as possible!

Input & Output

example_1.py โ€” Basic Case
$ Input: [3, 2, 4, 6]
โ€บ Output: 7
๐Ÿ’ก Note: We can transform the array to achieve XOR of 7. The numbers in binary are: 3=0011, 2=0010, 4=0100, 6=0110. The OR of all numbers is 0111=7, which is the maximum possible XOR since operations can only turn bits OFF.
example_2.py โ€” Single Element
$ Input: [1]
โ€บ Output: 1
๐Ÿ’ก Note: With only one element, the XOR is just that element itself. No operations can increase this value since we can only turn bits OFF.
example_3.py โ€” All Same Bits
$ Input: [7, 7, 7]
โ€บ Output: 7
๐Ÿ’ก Note: All numbers have the same bits (0111). The maximum XOR we can achieve is 7, which happens when only one number keeps all its bits and others are reduced to 0.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค nums[i] โ‰ค 108
  • Each operation can be applied any number of times

Visualization

Tap to expand
Digital Light Switch NeighborhoodHouse 3 (0011)Switches: 0 1 OFF OFFHouse 2 (0010)Switches: OFF 1 OFF OFFHouse 4 (0100)Switches: OFF OFF 2 OFFHouse 6 (0110)Switches: OFF 1 2 OFFOptimal ConfigurationAll Switch Positions ONOR = 0111 = Maximum XOR = 7๐Ÿ’ก Key InsightSince switches can only be turned OFF, the maximum illuminationis achieved by keeping ALL unique switch positions that arecurrently ON somewhere in the neighborhood (bitwise OR)!
Understanding the Visualization
1
Initial Houses
Each house has some lights on (set bits)
2
Operation Rules
You can only turn lights OFF, never ON
3
Optimal Strategy
Keep all unique light positions on across different houses
4
Maximum Illumination
OR of all houses gives maximum possible light combination
Key Takeaway
๐ŸŽฏ Key Insight: The operation can only reduce bits, so maximum XOR equals the OR of all numbers!
Asked in
Google 42 Microsoft 28 Amazon 35 Meta 19
23.4K Views
Medium Frequency
~15 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