jueves, febrero 22, 2024
InicioSoftware DevelopmentRely the variety of pair in Array with given XOR porperty A^A...

Rely the variety of pair in Array with given XOR porperty A[i]^A[j] = i^j


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

Given an array A[] with N parts, the duty is to search out the entire variety of pairs attainable with A[i] ^ A[j] = i ^ j, contemplating base-indexing 1 and (i, j) are distinct.

Examples:

Enter: arr[] = {4, 2, 3, 1}
Output: 2
Clarification: The array has 2 pairs: (4, 1) and (2, 3)

  • For (4, 1), 4^1 = 5 and their index 1^4 = 5
  • Equally, for (2, 3), 2^3 = 1 and their index 2^3 = 1

Method: This may be solved with the next thought:

Making use of fundamental XOR rules, we will discover 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 mainly want to search out the entire pair of parts attainable with the identical worth of A[i]^i, the place i is the index of the ingredient within the array.

Steps concerned within the implementation of code:

  • Calculate the XOR of arr[i] ^ (i). Retailer it within the map.
  • Improve the rely of pairs by checking the frequency of every key and making use of (n * (n-1)) /2.

Under is the Implementation of the above strategy:

C++

#embody <bits/stdc++.h>

utilizing namespace std;

  

int getPairCount(int arr[], int n)

{

    int rely = 0;

    map<int, int> mp;

  

    

    for (int i = 0; i < n; i++)

        mp[(arr[i] ^ (i + 1))]++;

  

    

    for (auto itr : mp)

        

        rely += ((itr.second) * (itr.second - 1)) / 2;

    return rely;

}

  

int major()

{

    int arr[] = { 4, 2, 3, 1 };

    int n = sizeof(arr) / sizeof(arr[0]);

  

    

    cout << getPairCount(arr, n);

    return 0;

}

Time Complexity: O(N), Since we have now to run the loop solely as soon as.
Auxiliary Area: O(N), Non permanent mapping of A[i]^i values.

RELATED ARTICLES

DEJA UNA RESPUESTA

Por favor ingrese su comentario!
Por favor ingrese su nombre aquí

Most Popular

Recent Comments