 1603832400

# Count pairs having Bitwise XOR less than K from given array

Given an array **arr[]**of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is less than K.

Examples:

Input:_ arr = {1, 2, 3, 5} , K = 5_

Output:_ 4_

Explanation:

Bitwise XOR of all possible pairs that satisfy the given conditions are:

arr ^ arr = 1 ^ 2 = 3

arr ^ arr = 1 ^ 3 = 2

arr ^ arr = 1 ^ 5 = 4

arr ^ arr = 3 ^ 5 = 1

Therefore, the required output is 4.

Input:_ arr[] = {3, 5, 6, 8}, K = 7_

Output:_ 3_

### Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The simplest approach to solve this problem is to traverse the given array and generate all possible pairs of the given array and for each pair, check if bitwise XOR of the pair is less than K or not. If found to be true, then increment the count of pairs having bitwise XOR less than K. Finally, print the count of such pairs obtained.

Time Complexity:O(N2)

Auxiliary Space:O(1)

Efficient Approach: The problem can be solved using Trie. The idea is to iterate over the given array and for each array element, count the number of elements present in the Trie whose bitwise XOR with the current element is less than K and insert the binary representation of the current element into the Trie. Finally, print the count of pairs having bitwise XOR less than K. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

• C++

`// C++ program to implement `

`// the above approach `

`#include <bits/stdc++.h> `

`**using**` `**namespace**` `std; `

`// Structure of Trie `

`**struct**` `TrieNode `

`{ `

`// Stores binary represention `

`// of numbers `

`TrieNode *child; `

`// Stores count of elements `

`// present in a node `

`**int**` `cnt; `

`// Function to initialize `

`// a Trie Node `

`TrieNode() { `

`child = child = NULL; `

`cnt = 0; `

`} `

`}; `

`// Function to insert a number into Trie `

`**void**` `insertTrie(TrieNode *root,` `**int**` `N) { `

`// Traverse binary representation of X `

`**for**` `(``**int**` `i = 31; i >= 0; i--) { `

`// Stores ith bit of N `

`**bool**` `x = (N) & (1 << i); `

`// Check if an element already `

`// present in Trie having ith bit x`

`**if**``(!root->child[x]) { `

`// Create a new node of Trie. `

`root->child[x] =` `**new**` `TrieNode(); `

`} `

`// Update count of elements `

`// whose ith bit is x `

`root->child[x]->cnt+= 1; `

`// Update root `

`root= root->child[x]; `

`} `

`} `

`// Function to count elements `

`// in Trie whose XOR with N `

`// less than K `

`**int**` `cntSmaller(TrieNode * root, `

`**int**` `N,` `**int**` `K) `

`{ `

`// Stores count of elements `

`// whose XOR with N less than K `

`**int**` `cntPairs = 0; `

`// Traverse binary representation `

`// of N and K in Trie `

`**for**` `(``**int**` `i = 31; i >= 0 && `

`root; i--) { `

`// Stores ith bit of N                         `

`**bool**` `x = N & (1 << i); `

`// Stores ith bit of K `

`**bool**` `y = K & (1 << i); `

`// If the ith bit of K is 1 `

`**if**` `(y) { `

`// If an element already `

`// present in Trie having `

`// ith bit (x)`

`**if**``(root->child[x]) {`

`cntPairs  +=`

`root->child[x]->cnt; `

`}`

`root = `

`root->child[1 - x]; `

`} `

`// If the ith bit of K is 0 `

`**else**``{ `

`// Update root `

`root = root->child[x]; `

`} `

`} `

`**return**` `cntPairs; `

`} `

`// Function to count pairs that `

`// satisfy the given conditions`

`**int**` `cntSmallerPairs(``**int**` `arr[],` `**int**` `N, `

`**int**` `K) { `

`// Create root node of Trie `

`TrieNode *root =` `**new**` `TrieNode(); `

`// Stores count of pairs that `

`// satisfy the given conditions `

`**int**` `cntPairs = 0; `

`// Traverse the given array `

`**for**``(``**int**` `i = 0;i < N; i++){ `

`// Update cntPairs `

`cntPairs += cntSmaller(root, `

`arr[i], K); `

`// Insert arr[i] into Trie `

`insertTrie(root, arr[i]); `

`} `

`**return**` `cntPairs; `

`} `

`// Driver Code `

`**int**` `main() `

`{ `

`**int**` `arr[] = {3, 5, 6, 8}; `

`**int**` `K= 7; `

`**int**` `N =` `**sizeof**``(arr) /` `**sizeof**``(arr); `

`cout<<cntSmallerPairs(arr, N, K); `

`} `

Output:

``````3
``````

Time Complexity:O(N * 32)

Auxiliary Space:O(N * 32)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #bit magic #mathematical #bitwise-xor #trie

## Buddha Community  1603832400

## Count pairs having Bitwise XOR less than K from given array

Given an array **arr[]**of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is less than K.

Examples:

Input:_ arr = {1, 2, 3, 5} , K = 5_

Output:_ 4_

Explanation:

Bitwise XOR of all possible pairs that satisfy the given conditions are:

arr ^ arr = 1 ^ 2 = 3

arr ^ arr = 1 ^ 3 = 2

arr ^ arr = 1 ^ 5 = 4

arr ^ arr = 3 ^ 5 = 1

Therefore, the required output is 4.

Input:_ arr[] = {3, 5, 6, 8}, K = 7_

Output:_ 3_

### Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Naive Approach: The simplest approach to solve this problem is to traverse the given array and generate all possible pairs of the given array and for each pair, check if bitwise XOR of the pair is less than K or not. If found to be true, then increment the count of pairs having bitwise XOR less than K. Finally, print the count of such pairs obtained.

Time Complexity:O(N2)

Auxiliary Space:O(1)

Efficient Approach: The problem can be solved using Trie. The idea is to iterate over the given array and for each array element, count the number of elements present in the Trie whose bitwise XOR with the current element is less than K and insert the binary representation of the current element into the Trie. Finally, print the count of pairs having bitwise XOR less than K. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

• C++

`// C++ program to implement `

`// the above approach `

`#include <bits/stdc++.h> `

`**using**` `**namespace**` `std; `

`// Structure of Trie `

`**struct**` `TrieNode `

`{ `

`// Stores binary represention `

`// of numbers `

`TrieNode *child; `

`// Stores count of elements `

`// present in a node `

`**int**` `cnt; `

`// Function to initialize `

`// a Trie Node `

`TrieNode() { `

`child = child = NULL; `

`cnt = 0; `

`} `

`}; `

`// Function to insert a number into Trie `

`**void**` `insertTrie(TrieNode *root,` `**int**` `N) { `

`// Traverse binary representation of X `

`**for**` `(``**int**` `i = 31; i >= 0; i--) { `

`// Stores ith bit of N `

`**bool**` `x = (N) & (1 << i); `

`// Check if an element already `

`// present in Trie having ith bit x`

`**if**``(!root->child[x]) { `

`// Create a new node of Trie. `

`root->child[x] =` `**new**` `TrieNode(); `

`} `

`// Update count of elements `

`// whose ith bit is x `

`root->child[x]->cnt+= 1; `

`// Update root `

`root= root->child[x]; `

`} `

`} `

`// Function to count elements `

`// in Trie whose XOR with N `

`// less than K `

`**int**` `cntSmaller(TrieNode * root, `

`**int**` `N,` `**int**` `K) `

`{ `

`// Stores count of elements `

`// whose XOR with N less than K `

`**int**` `cntPairs = 0; `

`// Traverse binary representation `

`// of N and K in Trie `

`**for**` `(``**int**` `i = 31; i >= 0 && `

`root; i--) { `

`// Stores ith bit of N                         `

`**bool**` `x = N & (1 << i); `

`// Stores ith bit of K `

`**bool**` `y = K & (1 << i); `

`// If the ith bit of K is 1 `

`**if**` `(y) { `

`// If an element already `

`// present in Trie having `

`// ith bit (x)`

`**if**``(root->child[x]) {`

`cntPairs  +=`

`root->child[x]->cnt; `

`}`

`root = `

`root->child[1 - x]; `

`} `

`// If the ith bit of K is 0 `

`**else**``{ `

`// Update root `

`root = root->child[x]; `

`} `

`} `

`**return**` `cntPairs; `

`} `

`// Function to count pairs that `

`// satisfy the given conditions`

`**int**` `cntSmallerPairs(``**int**` `arr[],` `**int**` `N, `

`**int**` `K) { `

`// Create root node of Trie `

`TrieNode *root =` `**new**` `TrieNode(); `

`// Stores count of pairs that `

`// satisfy the given conditions `

`**int**` `cntPairs = 0; `

`// Traverse the given array `

`**for**``(``**int**` `i = 0;i < N; i++){ `

`// Update cntPairs `

`cntPairs += cntSmaller(root, `

`arr[i], K); `

`// Insert arr[i] into Trie `

`insertTrie(root, arr[i]); `

`} `

`**return**` `cntPairs; `

`} `

`// Driver Code `

`**int**` `main() `

`{ `

`**int**` `arr[] = {3, 5, 6, 8}; `

`**int**` `K= 7; `

`**int**` `N =` `**sizeof**``(arr) /` `**sizeof**``(arr); `

`cout<<cntSmallerPairs(arr, N, K); `

`} `

Output:

``````3
``````

Time Complexity:O(N * 32)

Auxiliary Space:O(N * 32)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#advanced data structure #arrays #bit magic #mathematical #bitwise-xor #trie 1596999600

## Bitwise operations on Subarrays of size K

Given an array arr[] of positive integers and an number K, the task is to find the minimum and maximum values of Bitwise operation on elements of subarray of size K.

Examples:

Input:_ arr[]={2, 5, 3, 6, 11, 13}, k = 3_

Output:

Maximum AND = 2

Minimum AND = 0

Maximum OR = 15

Minimum OR = 7

Explanation:

Maximum AND is generated by subarray 3, 6 and 11, 3 & 6 & 11 = 2

Minimum AND is generated by subarray 2, 3 and 5, 2 & 3 & 5 = 0

Maximum OR is generated by subarray 2, 6 and 13, 2 | 6 | 13 = 15

Minimum OR is generated by subarray 2, 3 and 5, 2 | 3 | 5 = 7

Input:_ arr[]={5, 9, 7, 19}, k = 2_

Output:

Maximum AND = 3

Minimum AND = 1

Maximum OR = 23

Minimum OR = 13

Naive Approach: The naive approach is generate all possible subarrays of size K and check which of the above formed subarray will give the minimum and maximum Bitwise OR and AND.

Time Complexity: O(N2)

Auxiliary Space: O(K)

Efficient Approach: The idea is to use Sliding Window Technique to solve this problem. Below are the steps:

1. Traverse the prefix array of size K and for each array element go through it’s each bit and increase bit array (by maintaining an integer array bit of size 32) by 1 if it is set.
2. Convert this bit array to a decimal number lets say ans, and move the sliding window to the next index.
3. For newly addded element for the next subarray of size K, Iterate through each bit of newly added element and increase bit array by 1 if it is set.
4. For removing first element from the previous window, decrease bit array by 1 if it is set.
5. Update ans with minimum or maximum of the new decimal number generated by bit array.
• Below is the program to find the Maximum Bitwise OR subarray:

• `// C++ program for maximum values of`

• `// each bitwise OR operation on`

• `// element of subarray of size K`

• `#include <iostream>`

• `**using**` `**namespace**` `std;`

• `// Function to convert bit array to`

• `// decimal number`

• `**int**` `build_num(``**int**` `bit[])`

• `{`

• `**int**` `ans = 0;`

• `**for**` `(``**int**` `i = 0; i < 32; i++)`

• `**if**` `(bit[i])`

• `ans += (1 << i);`

• `**return**` `ans;`

• `}`

• `// Function to find  maximum values of`

• `// each bitwise OR operation on`

• `// element of subarray of size K`

• `**int**` `maximumOR(``**int**` `arr[],` `**int**` `n,` `**int**` `k)`

• `{`

• `// Maintain an integer array bit[]`

• `// of size 32 all initialized to 0`

• `**int**` `bit = { 0 };`

• `// Create a sliding window of size k`

• `**for**` `(``**int**` `i = 0; i < k; i++) {`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `}`

• `// Function call`

• `**int**` `max_or = build_num(bit);`

• `**for**` `(``**int**` `i = k; i < n; i++) {`

• `// Perform operation for`

• `// removed element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i - k] & (1 << j))`

• `bit[j]--;`

• `}`

• `// Perform operation for`

• `// added_element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `// Taking maximum value`

• `max_or = max(build_num(bit), max_or);`

• `}`

• `// Return the result`

• `**return**` `max_or;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `// Given array arr[]`

• `**int**` `arr[] = { 2, 5, 3, 6, 11, 13 };`

• `// Given subarray size K`

• `**int**` `k = 3;`

• `**int**` `n =` `**sizeof**` `arr /` `**sizeof**` `arr;`

• `// Function Call`

• `cout << maximumOR(arr, n, k);`

• `**return**` `0;`

• `}`

• Output:

``````15
``````
• Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32.

• Auxiliary Space: O(n)

• Below is the program to find the Minimum Bitwise OR subarray:

• `// C++ program for minimum values of`

• `// each bitwise OR operation on`

• `// element of subarray of size K`

• `#include <iostream>`

• `**using**` `**namespace**` `std;`

• `// Function to convert bit array`

• `// to decimal number`

• `**int**` `build_num(``**int**` `bit[])`

• `{`

• `**int**` `ans = 0;`

• `**for**` `(``**int**` `i = 0; i < 32; i++)`

• `**if**` `(bit[i])`

• `ans += (1 << i);`

• `**return**` `ans;`

• `}`

• `// Function to find  minimum values of`

• `// each bitwise OR operation on`

• `// element of subarray of size K`

• `**int**` `minimumOR(``**int**` `arr[],` `**int**` `n,` `**int**` `k)`

• `{`

• `// Maintain an integer array bit[]`

• `// of size 32 all initialized to 0`

• `**int**` `bit = { 0 };`

• `// Create a sliding window of size k`

• `**for**` `(``**int**` `i = 0; i < k; i++) {`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `}`

• `// Function call`

• `**int**` `min_or = build_num(bit);`

• `**for**` `(``**int**` `i = k; i < n; i++) {`

• `// Perform operation for`

• `// removed element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i - k] & (1 << j))`

• `bit[j]--;`

• `}`

• `// Perform operation for`

• `// added_element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `// Taking minimum value`

• `min_or = min(build_num(bit),`

• `min_or);`

• `}`

• `// Return the result`

• `**return**` `min_or;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `// Given array arr[]`

• `**int**` `arr[] = { 2, 5, 3, 6, 11, 13 };`

• `// Given subarray size K`

• `**int**` `k = 3;`

• `**int**` `n =` `**sizeof**` `arr /` `**sizeof**` `arr;`

• `// Function Call`

• `cout << minimumOR(arr, n, k);`

• `**return**` `0;`

• `}`

• Output:

``````7
``````
• Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32.

• Auxiliary Space: O(n)

• Below is the program to find the Maximum Bitwise AND subarray:

• `// C++ program for maximum values of`

• `// each bitwise AND operation on`

• `// element of subarray of size K`

• `#include <iostream>`

• `**using**` `**namespace**` `std;`

• `// Function to convert bit array`

• `// to decimal number`

• `**int**` `build_num(``**int**` `bit[],` `**int**` `k)`

• `{`

• `**int**` `ans = 0;`

• `**for**` `(``**int**` `i = 0; i < 32; i++)`

• `**if**` `(bit[i] == k)`

• `ans += (1 << i);`

• `**return**` `ans;`

• `}`

• `// Function to find maximum values of`

• `// each bitwise AND operation on`

• `// element of subarray of size K`

• `**int**` `maximumAND(``**int**` `arr[],` `**int**` `n,` `**int**` `k)`

• `{`

• `// Maintain an integer array bit[]`

• `// of size 32 all initialized to 0`

• `**int**` `bit = { 0 };`

• `// Create a sliding window of size k`

• `**for**` `(``**int**` `i = 0; i < k; i++) {`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `}`

• `// Function call`

• `**int**` `max_and = build_num(bit, k);`

• `**for**` `(``**int**` `i = k; i < n; i++) {`

• `// Perform operation for`

• `// removed element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i - k] & (1 << j))`

• `bit[j]--;`

• `}`

• `// Perform operation for`

• `// added element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `// Taking maximum value`

• `max_and = max(build_num(bit, k),`

• `max_and);`

• `}`

• `// Return the result`

• `**return**` `max_and;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `// Given array arr[]`

• `**int**` `arr[] = { 2, 5, 3, 6, 11, 13 };`

• `// Given subarray size K`

• `**int**` `k = 3;`

• `**int**` `n =` `**sizeof**` `arr /` `**sizeof**` `arr;`

• `// Function Call`

• `cout << maximumAND(arr, n, k);`

• `**return**` `0;`

• `}`

• Output:

``````2
``````
• Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32.

• Auxiliary Space: O(n)

• Below is the program to find the Minimum Bitwise AND subarray:

• `// C++ program for minimum values of`

• `// each bitwise AND operation on`

• `// elements of subarray of size K`

• `#include <iostream>`

• `**using**` `**namespace**` `std;`

• `// Function to convert bit array`

• `// to decimal number`

• `**int**` `build_num(``**int**` `bit[],` `**int**` `k)`

• `{`

• `**int**` `ans = 0;`

• `**for**` `(``**int**` `i = 0; i < 32; i++)`

• `**if**` `(bit[i] == k)`

• `ans += (1 << i);`

• `**return**` `ans;`

• `}`

• `// Function to find minimum values of`

• `// each bitwise AND operation on`

• `// element of subarray of size K`

• `**int**` `minimumAND(``**int**` `arr[],` `**int**` `n,` `**int**` `k)`

• `{`

• `// Maintain an integer array bit[]`

• `// of size 32 all initialized to 0`

• `**int**` `bit = { 0 };`

• `// Create a sliding window of size k`

• `**for**` `(``**int**` `i = 0; i < k; i++) {`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `}`

• `// Function call`

• `**int**` `min_and = build_num(bit, k);`

• `**for**` `(``**int**` `i = k; i < n; i++) {`

• `// Perform operation to removed`

• `// element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i - k] & (1 << j))`

• `bit[j]--;`

• `}`

• `// Perform operation to add`

• `// element`

• `**for**` `(``**int**` `j = 0; j < 32; j++) {`

• `**if**` `(arr[i] & (1 << j))`

• `bit[j]++;`

• `}`

• `// Taking minimum value`

• `min_and = min(build_num(bit, k),`

• `min_and);`

• `}`

• `// Return the result`

• `**return**` `min_and;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `// Given array arr[]`

• `**int**` `arr[] = { 2, 5, 3, 6, 11, 13 };`

• `// Given subarray size K`

• `**int**` `k = 3;`

• `**int**` `n =` `**sizeof**` `arr /` `**sizeof**` `arr;`

• `// Function Call`

• `cout << minimumAND(arr, n, k);`

• `**return**` `0;`

• `}`

• Output:

``````0
``````
• Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32.

• Auxiliary Space: O(n)

• Below is the program to find the Minimum Bitwise XOR subarray:

• `// C++ program to find the subarray`

• `/// with minimum XOR`

• `#include <bits/stdc++.h>`

• `**using**` `**namespace**` `std;`

• `// Function to find the minimum XOR`

• `// of the subarray of size K`

• `**void**` `findMinXORSubarray(``**int**` `arr[],`

• `**int**` `n,` `**int**` `k)`

• `{`

• `// K must be smaller than`

• `// or equal to n`

• `**if**` `(n < k)`

• `**return**``;`

• `// Initialize the beginning`

• `// index of result`

• `**int**` `res_index = 0;`

• `// Compute XOR sum of first`

• `// subarray of size K`

• `**int**` `curr_xor = 0;`

• `**for**` `(``**int**` `i = 0; i < k; i++)`

• `curr_xor ^= arr[i];`

• `// Initialize minimum XOR`

• `// sum as current xor`

• `**int**` `min_xor = curr_xor;`

• `// Traverse from (k+1)'th`

• `// element to n'th element`

• `**for**` `(``**int**` `i = k; i < n; i++) {`

• `// XOR with current item`

• `// and first item of`

• `// previous subarray`

• `curr_xor ^= (arr[i] ^ arr[i - k]);`

• `// Update result if needed`

• `**if**` `(curr_xor < min_xor) {`

• `min_xor = curr_xor;`

• `res_index = (i - k + 1);`

• `}`

• `}`

• `// Print the minimum XOR`

• `cout << min_xor <<` `"\n"``;`

• `}`

• `// Driver Code`

• `**int**` `main()`

• `{`

• `// Given array arr[]`

• `**int**` `arr[] = { 3, 7, 90, 20, 10, 50, 40 };`

• `// Given subarray size K`

• `**int**` `k = 3;`

• `**int**` `n =` `**sizeof**``(arr) /` `**sizeof**``(arr);`

• `// Function Call`

• `findMinXORSubarray(arr, n, k);`

• `**return**` `0;`

• `}`

• Output:

``````16
``````
• Time Complexity: O(n * B) where n is the size of the array and B is the integer array bit of size 32.
• Auxiliary Space: O(n)

#arrays #bit magic #competitive programming #bitwise-and #bitwise-or #bitwise-xor #subarray 1598366820

## How to Implement Bitwise Operations On Images Using OpenCV?

OpenCV is an image processing library created by intel which includes various packages and several functions in it. OpenCV is used to solve many problems in computer vision and machine learning applications and due to its large community, it is getting updated day by day. OpenCV can be implemented in C++, Python, Java programming languages, and different platforms like Linux, Windows, macOS.

In this article, we will demonstrate one of the interesting applications of OpenCV in performing bitwise operations on images.

• Bitwise Operators in Computer Vision
• Bitwise AND
• Bitwise OR
• Bitwise NOT
• Bitwise XOR

#### Bitwise Operators in Computer Vision

Bitwise operations can be used in image manipulations. These bitwise techniques are used in many computer vision applications like for creating masks of the image, adding watermarks to the image and it is possible to create a new image using these bitwise operators. These operations work on the individual pixels in the image to give accurate results compared with other morphing techniques in OpenCV.

Using the below code snippet, we will create two images – image1, image2 as input images on which the bitwise operations will be performed.

`import numpy as np`

`import cv2`

`from google.colab.patches import cv2_imshow`

`image1 = np.zeros((400, 400), dtype="uint8")`

`cv2.rectangle(image1, (100, 100), (250, 250), 255, -1)`

`cv2_imshow(image1)`

`image2 = np.zeros((400, 400), dtype="uint8")`

`cv2.circle(image2, (150, 150), 90, 255, -1)`

`cv2_imshow(image2)`

#developers corner #bitwise and #bitwise not #bitwise or #bitwise xor #opencv image processing 1598428800

## Construct a List using the given Q XOR queries

Given a list S that initially contains a single value 0. Below are the Q queries of the following types:

• 0 X: Insert X in the list
• 1 X: For every element A in S, replace it by A XOR X.

The task is to print all the element in the list in increasing order after performing the given Q queries.

Examples:

Input:_ Q[][] = { {0, 6}, {0, 3}, {0, 2}, {1, 4}, {1, 5} }_

Output:_ 1 2 3 7_

Explanation:

 (initial value)

[0 6] (add 6 to list)

[0 6 3] (add 3 to list)

[0 6 3 2] (add 2 to list)

[4 2 7 6] (XOR each element by 4)

[1 7 2 3] (XOR each element by 5)

Thus sorted order after performing queries is [1 2 3 7]

Input:_ Q[][]= {{0, 2}, {1, 3}, {0, 5} }_

Output:_ 1 3 5_

Explanation:

 (initial value)

[0 2] (add 2 to list)

[3 1] (XOR each element by 3)

[3 1 5] (add 5 to list)

Thus sorted order after performing queries is [1 3 5]

Naive Approach: The simplest approach to solve the problem is:

1. Initialize a list with 0 then traverse for each query and do the following:
• For query type 0 add given value in the list.
• For query type 1 traverse list and update every element with their respective Bitwise XOR with value.
1. After all the queries performed, print the final list in increasing order.

Time Complexity:_ O(N*Q), where N is the length of the list and Q is the number of queries_

Auxiliary Space:_ O(1)_

Efficient Approach: It is much easier to process the numbers in reverse order by keeping track of the cumulative Bitwise XOR working from right to left. Follow the steps below to solve the problem:

1. Initialize a variable xor with** 0.**
2. Iterate over the query array from right to left, add xor^value to the list while query type is 0 otherwise update xor with xor^value.
3. After traversing query add xor to the list and sort the final list.
4. Print the final list after the above operations.

Below is the implementation of the above approach:

• Java
• Python3
• C#

`// Java program for the above approach`

`**import**` `java.util.*;`

`**class**` `GFG {`

`// Function to return required list`

`// after performing all the queries`

`**static**` `List<Integer> ConstructList(``**int**``[][] Q)`

`{`

`// Store cumulative Bitwise XOR`

`**int**` `xor =` `0``;`

`// Initialize final list to return`

`List<Integer> ans =` `**new**` `ArrayList<>();`

`// Perform each query`

`**for**` `(``**int**` `i = Q.length -` `1``; i >=` `0``; i--) {`

`**if**` `(Q[i][``0``] ==` `0``)`

`ans.add(Q[i][``1``] ^ xor);`

`**else**`

`xor ^= Q[i][``1``];`

`}`

`// The initial value of 0`

`ans.add(xor);`

`// Sort the list`

`Collections.sort(ans);`

`// Return final list`

`**return**` `ans;`

`}`

`// Driver Code`

`**public**` `**static**` `**void**` `main(String[] args)`

`{`

`// Given Queries`

`**int**``[][] Q = {`

`{` `0``,` `6` `}, {` `0``,` `3` `}, {` `0``,` `2` `},`

`{` `1``,` `4` `}, {` `1``,` `5` `}`

`};`

`// Function Call`

`System.out.println(ConstructList(Q));`

`}`

`}`

Output:

``````[1, 2, 3, 7]

``````

Time Complexity:_ O(Q * log(Q))_, where Q is the number of queries.

Auxiliary Space:_ O(N)_, where N is the number of elements in the resultant list.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #bit magic #array-range-queries #bitwise-xor #google 1599117600

## XOR of all possible pairwise sum from two given Arrays

Given two arrays A[] and **B[] **of equal length, the task is to find the Bitwise XOR of pairwise sum of the given two arrays.

Examples:

Input:_ A[] = {1, 2}, B[] = {3, 4} _

_Output: __2 _

Explanation:

_Sum of all possible pairs are {4(1 + 3), 5(1 + 4), 5(2 + 3), 6(2 + 4)} _

XOR of all the pair sums = 4 ^ 5 ^ 5 ^ 6 = 2

_Input: __A[] = {4, 6, 0, 0, 3, 3}, B[] = {0, 5, 6, 5, 0, 3} _

_Output: _8

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

**Naive Approach: **The simplest approach to solve the problem is to generate all possible pairs from the two given arrays and calculate their respective sums and update XOR with the sum of pairs. Finally, print the XOR obtained.

Below is the implementation of the above approach:

### C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to calculate the sum of`

`// XOR of the sum of every pair`

`**int**` `XorSum(``**int**` `A[],` `**int**` `B[],` `**int**` `N)`

`{`

`// Stores the XOR of sums`

`// of every pair`

`**int**` `ans = 0;`

`// Iterate to generate all possible pairs`

`**for**` `(``**int**` `i = 0; i < N; i++) {`

`**for**` `(``**int**` `j = 0; j < N; j++) {`

`// Update XOR`

`ans = ans ^ (A[i] + B[j]);`

`}`

`}`

`// Return the answer`

`**return**` `ans;`

`}`

`// Driver Code`

`**int**` `main()`

`{`

`**int**` `A[] = { 4, 6, 0, 0, 3, 3 };`

`**int**` `B[] = { 0, 5, 6, 5, 0, 3 };`

`**int**` `N =` `**sizeof**` `A /` `**sizeof**` `A;`

`cout << XorSum(A, B, N) << endl;`

`**return**` `0;`

`}`

### Python3

`## Python3 program to implement`

`## the above approach`

`## Function to calculate the sum of`

`## XOR of the sum of every pair`

`**def**` `XorSum(A, B, N):`

`## Stores the XOR of sums`

`## of every pair`

`ans` `**=**` `0`

`## Iterate to generate all `

`## possible pairs`

`**for**` `i` `**in**` `range``(N):`

`**for**` `j` `**in**` `range``(N):`

`## Update XOR`

`ans` `**=**` `ans ^ (A[i]` `**+**` `B[j])`

`## Return the answer`

`**return**` `ans`

`## Driver Code`

`**if**` `__name__` `**==**` `"__main__"``:`

`A` `**=**` `[` `4``,` `6``,` `0``,` `0``,` `3``,` `3` `]`

`B` `**=**` `[` `0``,` `5``,` `6``,` `5``,` `0``,` `3` `]`

`N` `**=**` `len``(A)`

`print` `(XorSum(A, B, N))`

`## This code is contributed by chitranayal`

Output:

``````8
``````

Time Complexity:_ O(N2) _

Auxiliary Space:_ O(1)_

**Efficient Approach: **The above approach can be optimized using Bit Manipulation technique. Follow the steps below to solve the problem:

• Considering only the Kth bit, the task is to count the number of pairs (i, j) such that the Kth bit of (Ai + Bj) is set.
• If this number is odd, add** X = 2k** to the answer. We are only interested in the values of (ai, bj) in modulo** 2X**.
• Thus, replace ai with ai % (2X) and bj with bj % (2X), and assume that ai and bj < 2X.
• There are two cases when the kth bit of (ai + bj) is set:
• x ≤ ai + bj < 2x
• 3x ≤ ai + bj < 4x
• Hence, sort b[] in increasing order. For a fixed i, the set of j that satisfies X ≤ (ai +bj) < 2X forms an interval.
• Therefore, count the number of such j by Binary search. Similarly, handle the second case.

Below is the implementation of the above approach:

### C++

`// C++ Program to implement`

`// the above approach`

`#include <bits/stdc++.h>`

`**using**` `**namespace**` `std;`

`// Function to calculate the`

`// XOR of the sum of every pair`

`**int**` `XorSum(``**int**` `A[],` `**int**` `B[],` `**int**` `N)`

`{`

`// Stores the maximum bit`

`**const**` `**int**` `maxBit = 29;`

`**int**` `ans = 0;`

`// Look for all the k-th bit`

`**for**` `(``**int**` `k = 0; k < maxBit; k++) {`

`// Stores the modulo of`

`// elements B[] with (2^(k+1))`

`**int**` `C[N];`

`**for**` `(``**int**` `i = 0; i < N; i++) {`

`// Calculate modulo of`

`// array B[] with (2^(k+1))`

`C[i] = B[i] % (1 << (k + 1));`

`}`

`// Sort the array C[]`

`sort(C, C + N);`

`// Stores the total number`

`// whose k-th bit is set`

`**long**` `**long**` `count = 0;`

`**long**` `**long**` `l, r;`

`**for**` `(``**int**` `i = 0; i < N; i++) {`

`// Calculate and store the modulo`

`// of array A[] with (2^(k+1))`

`**int**` `x = A[i] % (1 << (k + 1));`

`// Lower bound to count the number`

`// of elements having k-th bit in`

`// the range (2^k - x, 2* 2^(k) - x)`

`l = lower_bound(C,`

`C + N,`

`(1 << k) - x)`

`- C;`

`r = lower_bound(C,`

`C + N,`

`(1 << k) * 2 - x)`

`- C;`

`// Add total number i.e (r - l)`

`// whose k-th bit is one`

`count += (r - l);`

`// Lower bound to count the number`

`// of elements having k-th bit in`

`// range (3 * 2^k - x, 4*2^(k) - x)`

`l = lower_bound(C,`

`C + N,`

`(1 << k) * 3 - x)`

`- C;`

`r = lower_bound(C,`

`C + N,`

`(1 << k) * 4 - x)`

`- C;`

`count += (r - l);`

`}`

`// If count is even, Xor of`

`// k-th bit becomes zero, no`

`// need to add to the answer.`

`// If count is odd, only then,`

`// add to the final answer`

`**if**` `(count & 1)`

`ans += (1 << k);`

`}`

`// Return answer`

`**return**` `ans;`

`}`

`// Driver code`

`**int**` `main()`

`{`

`**int**` `A[] = { 4, 6, 0, 0, 3, 3 };`

`**int**` `B[] = { 0, 5, 6, 5, 0, 3 };`

`**int**` `N =` `**sizeof**` `A /` `**sizeof**` `A;`

`// Function call`

`cout << XorSum(A, B, N) << endl;`

`**return**` `0;`

`}`

Output:

``````8
``````

Time Complexity:_ O(NlogN) _

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #bit magic #mathematical #sorting #binary search #bitwise-xor