LeetCode: Find Xor-Beauty of Array
Problem:
https://leetcode.com/problems/find-xor-beauty-of-array/description/
Code:
class Solution:
def xorBeauty(self, nums: List[int]) -> int:
result=0
for n in nums:
result = result ^ n
return result
Key Points:
The problem looks complex in the description, but the final math simplifies a lot.
The XOR-beauty of the array is simply: nums[0] ^ nums[1] ^ nums[2] ^ ... ^ nums[n-1]
This works because all the extra operations in the original formula cancel out.
XOR rules that make this work:
x ^ x = 0 → duplicates cancel.
x ^ 0 = x → does not change the value.
XOR is commutative & associative → order doesn’t matter.
Loop through the array and XOR every number into “result”.
Whatever remains at the end is the XOR-beauty.
Time: O(n)
Space: O(1)