Count the number of pair in Array with given XOR porperty A[i]^A[j] = i^j
Given an array A[] with N elements, the task is to find the total number of pairs possible with A[i] ^ A[j] = i ^ j, considering base-indexing 1 and (i, j) are distinct.
Examples:
Input: arr[] = {4, 2, 3, 1}
Output: 2
Explanation: The array has 2 pairs: (4, 1) and (2, 3)
- For (4, 1), 4^1 = 5 and their index 1^4 = 5
- Similarly, for (2, 3), 2^3 = 1 and their index 2^3 = 1
Approach: This can be solved with the following idea:
Applying basic XOR principles, we can find that
Given: A[i]^A[j] = i^j
- A[i] ^ A[j] ^ A[j] = i ^ j ^ A[j]
- A[i] ^ i = i ^ i ^ j ^ A[j]
- A[i] ^ i = A[j] ^ j
Thus, we basically need to find the total pair of elements possible with the same value of A[i]^i, where i is the index of the element in the array.
Steps involved in the implementation of code:
- Calculate the XOR of arr[i] ^ (i). Store it in the map.
- Increase the count of pairs by checking the frequency of each key and applying (n * (n-1)) /2.
Below is the Implementation of the above approach:
C++
|
Time Complexity: O(N), Since we have to run the loop only once.
Auxiliary Space: O(N), Temporary mapping of A[i]^i values.
Given an array A[] with N elements, the task is to find the total number of pairs possible with A[i] ^ A[j] = i ^ j, considering base-indexing 1 and (i, j) are distinct.
Examples:
Input: arr[] = {4, 2, 3, 1}
Output: 2
Explanation: The array has 2 pairs: (4, 1) and (2, 3)
- For (4, 1), 4^1 = 5 and their index 1^4 = 5
- Similarly, for (2, 3), 2^3 = 1 and their index 2^3 = 1
Approach: This can be solved with the following idea:
Applying basic XOR principles, we can find that
Given: A[i]^A[j] = i^j
- A[i] ^ A[j] ^ A[j] = i ^ j ^ A[j]
- A[i] ^ i = i ^ i ^ j ^ A[j]
- A[i] ^ i = A[j] ^ j
Thus, we basically need to find the total pair of elements possible with the same value of A[i]^i, where i is the index of the element in the array.
Steps involved in the implementation of code:
- Calculate the XOR of arr[i] ^ (i). Store it in the map.
- Increase the count of pairs by checking the frequency of each key and applying (n * (n-1)) /2.
Below is the Implementation of the above approach:
C++
|
Time Complexity: O(N), Since we have to run the loop only once.
Auxiliary Space: O(N), Temporary mapping of A[i]^i values.