Find Xor-Beauty of Array - Problem

You are given a 0-indexed integer array nums. Your task is to find the XOR-beauty of this array through a fascinating bit manipulation process.

Here's how it works:

  • For any three indices i, j, and k, we define an effective value as: ((nums[i] | nums[j]) & nums[k])
  • The XOR-beauty is the XOR of all possible effective values from every triplet combination

Example: If nums = [1, 4], we need to consider all 8 possible triplets: (0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)

Goal: Return the XOR-beauty of the array efficiently. Can you find a pattern to avoid checking all O(nยณ) triplets?

Note: | represents bitwise OR, & represents bitwise AND

Input & Output

example_1.py โ€” Simple Case
$ Input: nums = [1, 4]
โ€บ Output: 5
๐Ÿ’ก Note: All possible triplets: (0,0,0)โ†’1, (0,0,1)โ†’0, (0,1,0)โ†’1, (0,1,1)โ†’4, (1,0,0)โ†’1, (1,0,1)โ†’0, (1,1,0)โ†’1, (1,1,1)โ†’4. XOR all: 1โŠ•0โŠ•1โŠ•4โŠ•1โŠ•0โŠ•1โŠ•4 = 5. Optimized: 1โŠ•4 = 5
example_2.py โ€” Single Element
$ Input: nums = [15]
โ€บ Output: 15
๐Ÿ’ก Note: Only one possible triplet (0,0,0): (15|15)&15 = 15&15 = 15. Optimized: just return 15
example_3.py โ€” Zeros
$ Input: nums = [0, 0]
โ€บ Output: 0
๐Ÿ’ก Note: All triplets result in 0: (0|0)&0 = 0. XOR of all zeros is 0. Optimized: 0โŠ•0 = 0

Visualization

Tap to expand
๐ŸŽจ The XOR Beauty Transformation142Input ArrayBrute Force ApproachGenerate all nยณ tripletsCalculate each (nums[i]|nums[j])&nums[k]XOR all results โ†’ Answerโœจ Optimized ApproachXOR cancellation eliminates complexityOnly diagonal contributions surviveResult: nums[0] โŠ• nums[1] โŠ• nums[2]Time: O(nยณ) - Slow!Space: O(1)Time: O(n) - Lightning Fast! โšกSpace: O(1)๐ŸŽฏ Final Answer1 โŠ• 4 โŠ• 2 = 7
Understanding the Visualization
1
Generate All Triplets
Consider every possible combination of 3 indices (i,j,k)
2
Calculate Effective Values
For each triplet: (nums[i] | nums[j]) & nums[k]
3
XOR Cancellation Magic
Most values cancel out due to XOR properties
4
Elegant Result
Only the XOR of individual elements remains
Key Takeaway
๐ŸŽฏ Key Insight: XOR's magical self-canceling property (a โŠ• a = 0) eliminates the need to compute all nยณ triplets. The mathematical beauty lies in recognizing that only the individual array elements matter in the final result!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array to XOR all elements

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using one variable to accumulate result

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค nums[i] โ‰ค 109
  • Array elements can be zero
  • All operations fit within 32-bit integers
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
32.4K Views
Medium Frequency
~15 min Avg. Time
1.5K 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