We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Xor-Beauty of Array

Difficulty: Medium


Problem Description

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.


Key Insights

  • The effective value combines bitwise OR and AND operations, which can be efficiently computed.
  • The brute-force approach involves checking all combinations of triplets, which could be computationally expensive.
  • Observing the patterns in bit manipulation can help optimize the calculations.
  • The properties of XOR can lead to simplifications in aggregating results.

Space and Time Complexity

Time Complexity: O(n^3) in the naive approach, but can be optimized with bit manipulation.
Space Complexity: O(1) if we only use a few extra variables for calculations.


Solution

To solve the problem, we can iterate through all possible triplets (i, j, k) in the array nums. For each triplet, we compute the effective value using the formula ((nums[i] | nums[j]) & nums[k]) and maintain a running XOR of these effective values. Given the constraints, we need to consider optimizations that can reduce the number of operations through effective bit manipulation.


Code Solutions

def xor_beauty(nums):
    n = len(nums)
    result = 0
    for i in range(n):
        for j in range(n):
            for k in range(n):
                effective_value = (nums[i] | nums[j]) & nums[k]
                result ^= effective_value
    return result
← Back to All Questions