Skip to main content

Command Palette

Search for a command to run...

LeetCode: Find Xor-Beauty of Array

Published
1 min read

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:

    1. x ^ x = 0 → duplicates cancel.

    2. x ^ 0 = x → does not change the value.

    3. 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)