703039. Count Pairs Odd Xor
Basic
Count Pairs Odd Xor0308
Summary
The problem "Count Pairs Odd Xor" involves counting pairs in an array where the XOR operation between two elements is odd. This problem requires a basic understanding of mathematical operations and array manipulation.
Detailed Explanation
To solve this problem, we will iterate through the array and use a variable to keep track of the count of pairs with odd XOR. We will also keep track of the current element's XOR with all previous elements. If the XOR is odd, we increment the count.
Here is the step-by-step breakdown:
- Initialize a variable
countto 0. - Iterate through the array from the second element (index 1) to the end.
- For each element at index
i, calculate its XOR with all previous elements (xor_val = arr[0] ^ arr[1] ^ ... ^ arr[i-1]). - If the calculated XOR value is odd, increment the
count. - Return the final count.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only use a constant amount of space to store the variables.
Optimized Solutions
Java
public int countPairsOddXor(int[] arr) {
int count = 0;
int xor_val = 0;
for (int i = 1; i < arr.length; i++) {
xor_val ^= arr[i-1];
if ((xor_val & 1) == 1) {
count++;
}
}
return count;
}