Similar Problems

Similar Problems not available

Find Xor Beauty Of Array - Leetcode Solution

Companies:

LeetCode:  Find Xor Beauty Of Array Leetcode Solution

Difficulty: Medium

Topics: math bit-manipulation array  

Problem:

The beauty of an array is the sum of |nums[i]-nums[j]| where 0 <= i < j < nums.length.

Return the sum of beauty of all possible sub-arrays of nums.

Example:

Input: nums = [1,2,3] Output: 2 Explanation: The beauty of the array is |1-2|+|1-3|+|2-3| = 2. For all sub-arrays: [1] = 0 [1,2] = 1 [1,2,3] = 2 [2] = 0 [2,3] = 1 [3] = 0 Sum of all possible beauty values is 2.

Solution:

The brute-force solution is to find all possible sub-arrays of the given array and calculate their beauty value using the given formula. But the number of sub-arrays will be O(n^2), and calculating the beauty value for each sub-array will take O(n^2) time. Therefore, the overall time complexity of the brute-force solution will be O(n^4).

To optimize the time complexity of the solution, we can use the properties of the XOR operator. The XOR operator returns true (1) when two bits are different and false (0) when two bits are the same. Therefore, to calculate the XOR beauty of an array, we need to calculate the XOR of all possible pairs of elements in the array.

We can use a nested loop to iterate through all possible pairs of elements in the array. For each pair of elements, we can calculate their XOR and add it to a running beauty sum. Finally, we return the beauty sum as the answer.

Code:

class Solution {
public:
    int beautySum(vector<int>& nums) {
        int res = 0;
        for (int i = 0; i < nums.size(); i++) {
            int XOR = 0;
            for (int j = i+1; j < nums.size(); j++) {
                XOR ^= nums[j-1];
                res += (XOR == nums[j]);
            }
        }
        return res;
    }
};

Explanation:

In the above code, we use two nested loops to iterate through all possible pairs of elements in the given array. For each pair, we calculate their XOR value by using the XOR operator. We add the XOR value to a running sum if it equals the next element in the array.

The outer loop starts from the first element in the array and goes up to the second-last element. The inner loop starts from the element after the outer loop index and goes up to the last element in the array.

In the inner loop, we calculate the XOR value of the elements up to the current index and XOR it with the element at the current index. We then check if the XOR value equals the next element in the array. If it does, we add 1 to the running sum.

Finally, we return the running sum as the answer.

Find Xor Beauty Of Array Solution Code

1