Find Xor-Beauty of Array
MedPrompt
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 | val2is bitwise OR ofval1andval2.val1 & val2is bitwise AND ofval1andval2.
Example 1:
Input: nums = [1,4]
Output: 5
Explanation:
The triplets and their corresponding effective values are listed below:
- (0,0,0) with effective value ((1 | 1) & 1) = 1
- (0,0,1) with effective value ((1 | 1) & 4) = 0
- (0,1,0) with effective value ((1 | 4) & 1) = 1
- (0,1,1) with effective value ((1 | 4) & 4) = 4
- (1,0,0) with effective value ((4 | 1) & 1) = 1
- (1,0,1) with effective value ((4 | 1) & 4) = 4
- (1,1,0) with effective value ((4 | 4) & 1) = 0
- (1,1,1) with effective value ((4 | 4) & 4) = 4
Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.Example 2:
The xor-beauty of the given array is 34.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 109
Approaches
2 approaches with complexity analysis and trade-offs.
A straightforward approach that directly implements the problem description. It iterates through all nnn possible triplets of indices (i, j, k) and calculates the effective value for each. The xor-beauty is computed by XORing all these effective values together.
Algorithm
- Initialize a variable,
xorBeauty, to 0. This will store the cumulative XOR sum. - Use a loop for index
ifrom0ton-1, wherenis the length of thenumsarray. - Inside this loop, nest another loop for index
jfrom0ton-1. - Inside the second loop, nest a third loop for index
kfrom0ton-1. - In the innermost loop, we have a valid triplet
(i, j, k). Calculate the effective value:value = (nums[i] | nums[j]) & nums[k]. - Update the
xorBeautyby XORing it with thevalue:xorBeauty ^= value. - After the three loops have finished,
xorBeautywill contain the XOR sum of all effective values, which is the desired result.
Walkthrough
This approach is a direct translation of the problem statement into code. We need to find the XOR sum of ((nums[i] | nums[j]) & nums[k]) for all possible combinations of indices i, j, and k.
class Solution { public int xorBeauty(int[] nums) { int n = nums.length; int xorBeauty = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { int effectiveValue = (nums[i] | nums[j]) & nums[k]; xorBeauty ^= effectiveValue; } } } return xorBeauty; }}Complexity
Time
O(n^3), where n is the number of elements in the `nums` array. This is because there are three nested loops, each running `n` times.
Space
O(1), as we only use a constant amount of extra space for loop counters and the result variable.
Trade-offs
Pros
Simple to understand and implement directly from the problem statement.
Cons
Extremely inefficient due to its cubic time complexity.
Will result in a 'Time Limit Exceeded' (TLE) error for the given constraints (n up to 10^5).
This approach leverages the properties of bitwise operations (XOR, OR, AND) to simplify the complex expression for xor-beauty. Instead of calculating the value for each of the n^3 triplets, we can find a much simpler equivalent expression, which turns out to be the XOR sum of all elements in the array.
Algorithm
- Initialize a variable
resultto 0. - Iterate through each number
numin thenumsarray. - Update the result by XORing it with the current number:
result ^= num. - After the loop, return
result.
Walkthrough
The xor-beauty is defined as the XOR sum of ((nums[i] | nums[j]) & nums[k]) over all possible triplets (i, j, k). Let's denote this sum by X.
X = ⨁_{0 <= i, j, k < n} ((nums[i] | nums[j]) & nums[k])
The key to solving this problem efficiently is to simplify this expression using the properties of bitwise operations.
- Distributive Property of AND over OR: We know that
(a | b) & c = (a & c) | (b & c). Applying this to our term:((nums[i] | nums[j]) & nums[k]) = (nums[i] & nums[k]) | (nums[j] & nums[k]) - Rewriting the Sum: The total XOR sum can be rewritten by substituting this back:
X = ⨁_{i,j,k} [ (nums[i] & nums[k]) | (nums[j] & nums[k]) ] - Simplifying the Inner Sums: Let's fix
kand analyze the sum overiandj. Leta_p = nums[p] & nums[k]. The sum for a fixedkisS_k = ⨁_{i,j} (a_i | a_j).- In this sum, for any pair of distinct indices
pandq, the term(a_p | a_q)appears, and so does(a_q | a_p). Since(a_p | a_q) = (a_q | a_p), their XOR is(a_p | a_q) ^ (a_q | a_p) = 0. - This means all terms where
i ≠ jcancel each other out in pairs. - The only remaining terms are the "diagonal" ones where
i = j:S_k = ⨁_{i} (a_i | a_i) = ⨁_{i} a_i.
- In this sum, for any pair of distinct indices
- Substituting Back: Replacing
a_iwith its definition, we getS_k = ⨁_{i} (nums[i] & nums[k]). - Summing over k: The total xor-beauty
Xis the XOR sum of allS_k:X = ⨁_{k} S_k = ⨁_{k} [ ⨁_{i} (nums[i] & nums[k]) ] - Swapping Summation Order: The order of XORing doesn't matter, so we can swap the summations:
X = ⨁_{i} [ ⨁_{k} (nums[i] & nums[k]) ] - Distributive Property of AND over XOR: A less common but valid property is
a & (b ^ c) = (a & b) ^ (a & c). Applying this to the inner sum⨁_{k} (nums[i] & nums[k]), we get:⨁_{k} (nums[i] & nums[k]) = nums[i] & (⨁_{k} nums[k]) - Final Simplification: Let
XOR_ALL = ⨁_{p=0}^{n-1} nums[p]. The expression forXbecomes:X = ⨁_{i} (nums[i] & XOR_ALL)Applying the distributive property again:X = (⨁_{i} nums[i]) & XOR_ALLSubstituting the definition ofXOR_ALL:X = XOR_ALL & XOR_ALL = XOR_ALLThis remarkable simplification shows that the complex-looking xor-beauty is just the XOR sum of all elements in the array.
class Solution { public int xorBeauty(int[] nums) { int xorSum = 0; for (int num : nums) { xorSum ^= num; } return xorSum; }}Complexity
Time
O(n), where n is the number of elements in the `nums` array. We only need to iterate through the array once.
Space
O(1), as we only use a constant amount of extra space for the result variable.
Trade-offs
Pros
Extremely efficient with a linear time complexity.
Simple to implement once the mathematical simplification is understood.
Easily passes the given constraints.
Cons
The derivation of the simplified formula is non-trivial and requires a good understanding of bitwise properties, making it less intuitive at first glance.
Solutions
Solution
class Solution {public int xorBeauty(int[] nums) { int ans = 0; for (int x : nums) { ans ^= x; } return ans; }}class Solution {public: int xorBeauty(vector<int> &nums) { int ans = 0; for (auto &x : nums) { ans ^= x; } return ans; }};class Solution: def xorBeauty(self, nums: List[int]) -> int: return reduce(xor, nums)Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.