VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-quadruples-four-arrays-xor-equals-x/

⇱ Count all Quadruples from four arrays such that their XOR equals to 'x' - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count all Quadruples from four arrays such that their XOR equals to 'x'

Last Updated : 23 Jul, 2025

Given four arrays and an integer x, find the number of quadruples which satisfy a^b^c^d = x, where a belongs from Arr1, b belongs from Arr2, c belongs from Arr3, d belongs from Arr4.

Examples : 

Input : x = 0;
 a[] = { 1 , 10 };
 b[] = { 1 , 10 };
 c[] = { 1 , 10 };
 d[] = { 1 , 10 };
Output : 4
Explanation: There are total 8 Quadruples
with XOR value equals to 0.
{1, 1, 1, 1}, {10, 10, 10, 10}, {1, 1, 10, 10},
{10, 10, 1, 1}, {10, 1, 10, 1}, {1, 10, 1, 10},
{1, 10, 10, 1}, {10, 1, 1, 10}

Input : x = 3
 a[] = {0, 1}
 b[] = {2, 0}
 c[] = {0, 1}
 d[] = {0, 1}
Output : 4
Explanation: There are total 4 Quadruples
with XOR value equals to 3.
{0, 2, 0, 1}, {1, 2, 0, 0}, {0, 2, 1, 0},
{1, 2, 1, 1}

Method 1(Naive approach): It can be done using 4 loops, covering every quadruple and checking whether it is equal to x or not. 

Implementation:


Output
4

Time Complexity: O(n4
Auxiliary Space: O(1)

Method 2 (Efficient Approach):

The idea is to use meet in the middle algorithm.
For this, observe the pattern below:
a ^ b ^ c ^ d = x
XOR c and d both sides 
a ^ b ^ c ^ d ^ c ^ d = x ^ c ^ d
Since, c ^ c = 0 and d ^ d = 0
a ^ b ^ 0 ^ 0 = x ^ c ^ d
That is, a ^ b = x ^ c ^ d

Now, we just have to compute a ^ b and x ^ c ^ d which can be computed in O(n2) each and then find elements by using binary search.

Implementation:


Output
4

Time Complexity: O(n2log(n)) 
Auxiliary Space: O(n2)

Comment
Article Tags: