Find Xor-Beauty of Array - Problem

You are given a 0-indexed integer array nums.

The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]).

The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n.

Return the xor-beauty of nums.

Note that:

  • val1 | val2 is bitwise OR of val1 and val2.
  • val1 & val2 is bitwise AND of val1 and val2.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,4]
Output: 1
💡 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)→4, (1,1,0)→0, (1,1,1)→4. XOR result: 1⊕0⊕1⊕4⊕1⊕4⊕0⊕4 = 1
Example 2 — Single Element
$ Input: nums = [15]
Output: 15
💡 Note: Only one triplet possible: (0,0,0) gives (15|15)&15 = 15&15 = 15
Example 3 — Three Elements
$ Input: nums = [1,2,3]
Output: 2
💡 Note: Calculate all 27 possible triplets and XOR their effective values together

Constraints

  • 1 ≤ nums.length ≤ 300
  • 1 ≤ nums[i] ≤ 108

Visualization

Tap to expand
Find Xor-Beauty of Array INPUT nums array: 1 i=0 4 i=1 Binary Form: 1 = 001 4 = 100 All triplets (i,j,k): (0,0,0), (0,0,1), (0,1,0) (0,1,1), (1,0,0), (1,0,1) (1,1,0), (1,1,1) Formula: (nums[i]|nums[j])&nums[k] n = 2, total triplets = 8 ALGORITHM STEPS 1 Key Observation XOR of all triplets simplifies to XOR of all elements! 2 Math Proof Each pair (i,j) appears with all k values, canceling out 3 Simplification Result = nums[0] XOR nums[1] XOR ... XOR nums[n-1] 4 Calculation 1 XOR 4 = 001 XOR 100 001 (1) XOR 100 (4) = 101 (5) Wait: 1 XOR 4 = 5 FINAL RESULT XOR-Beauty Calculation: (0,0,0): (1|1)&1 = 1 (0,0,1): (1|1)&4 = 0 (0,1,0): (1|4)&1 = 1 (0,1,1): (1|4)&4 = 4 (1,0,0): (4|1)&1 = 1 (1,0,1): (4|1)&4 = 4 (1,1,0): (4|4)&1 = 0 (1,1,1): (4|4)&4 = 4 XOR all: 1^0^1^4^1^4^0^4 = 1 XOR-Beauty: 1 OK - Output verified! Key Insight: The XOR-beauty formula simplifies mathematically! Due to XOR properties, when we XOR all triplet effective values, most terms cancel out. The optimal O(n) solution: simply XOR all array elements. Time: O(n) | Space: O(1) | Avoid O(n^3) brute force by using mathematical insight. TutorialsPoint - Find Xor-Beauty of Array | Optimal Solution
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~25 min Avg. Time
580 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