Similar Problems
Similar Problems not available
Find Xor Sum Of All Pairs Bitwise And - Leetcode Solution
Companies:
LeetCode: Find Xor Sum Of All Pairs Bitwise And Leetcode Solution
Difficulty: Hard
Topics: math bit-manipulation array
Problem Statement:
Given an integer array nums, return the sum of XOR of all pairs (i, j) such that i < j.
Example 1:
Input: nums = [1,4,2,3] Output: 20 Explanation: The XOR sums for all pairs are:
- (1 XOR 4) = 5
- (1 XOR 2) = 3
- (1 XOR 3) = 2
- (4 XOR 2) = 6
- (4 XOR 3) = 7
- (2 XOR 3) = 1 The sum of XOR sums for all pairs is 5 + 3 + 2 + 6 + 7 + 1 = 24.
Example 2:
Input: nums = [3,6,8,10] Output: 28 Explanation: The XOR sums for all pairs are:
- (3 XOR 6) = 5
- (3 XOR 8) = 11
- (3 XOR 10) = 9
- (6 XOR 8) = 14
- (6 XOR 10) = 12
- (8 XOR 10) = 2 The sum of XOR sums for all pairs is 5 + 11 + 9 + 14 + 12 + 2 = 53.
Approach:
For the given problem, we can use the bitwise AND operator to check for the common set bits which will contribute towards the XOR sum. We can use a nested loop to calculate the XOR sum for each pair (i, j) where i < j.
The algorithm can be explained as follows:
- Initialize the XOR sum variable as 0.
- For each i from 0 to n-2: a. For each j from i+1 to n-1: i. Calculate the bitwise AND of nums[i] and nums[j]. ii. Calculate the XOR of the above result with the current XOR sum variable.
- Return the final XOR sum variable.
Code:
public int getXORSum(int[] nums) { int n = nums.length; int xorSum = 0; for(int i=0; i<n-1; i++){ for(int j=i+1; j<n; j++){ xorSum += (nums[i] & nums[j]) ^ xorSum; } } return xorSum; }
Time Complexity:
The time complexity of the above algorithm is O(n^2) because of the nested loop used.
Space Complexity:
The space complexity of the above algorithm is O(1) because we are not using any additional data structures.
Find Xor Sum Of All Pairs Bitwise And Solution Code
1