Given an array arr[] of N integers such that any two adjacent elements in the array differ at only one position in their binary representation. The task is to find whether there exists a quadruple (arr[i], arr[j], arr[k], arr[l]) such that arr[i] ^ arr[j] ^ arr[k] ^ arr[l] = 0. Here ^ denotes the bitwise xor operation and 1 ? i < j < k < l ? N.
Examples:Â
Â
Input: arr[] = {1, 3, 7, 3}Â
Output: NoÂ
1 ^ 3 ^ 7 ^ 3 = 6
Input: arr[] = {1, 0, 2, 3, 7}Â
Output: YesÂ
1 ^ 0 ^ 2 ^ 3 = 0Â
Â
Â
Â
- Naive approach: Check for all possible quadruples whether their xor is zero or not. But the time complexity of such a solution would be N4, for all N.Â
Time Complexity:Â
Â
- Efficient Approach (O(N4), for N ≤ 130): We can Say that for array length more than or equal to 130 we can have at least 65 adjacent pairs each denoting xor of two elements. Here it is given that all adjacent elements differ at only one position in their binary form thus there would result in only one set bit. Since we have only 64 possible positions, we can say that at least two pairs will have the same xor. Thus, xor of these 4 integers will be 0. For N < 130 we can use the naive approach.
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
const int MAX = 130;Â
// Function that returns true if the array// contains a valid quadruplet pairbool validQuadruple(int arr[], int n){Â
    // We can always find a valid quadruplet pair    // for array size greater than MAX    if (n >= MAX)        return true;Â
    // For smaller size arrays, perform brute force    for (int i = 0; i < n; i++)        for (int j = i + 1; j < n; j++)            for (int k = j + 1; k < n; k++)                for (int l = k + 1; l < n; l++) {                    if ((arr[i] ^ arr[j] ^ arr[k] ^ arr[l]) == 0) {                        return true;                    }                }    return false;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 0, 2, 3, 7 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    if (validQuadruple(arr, n))        cout << "Yes";    else        cout << "No";Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;import java.lang.*;import java.io.*;Â
class GFG{Â
static int MAX = 130; Â
// Function that returns true if the array // contains a valid quadruplet pair static boolean validQuadruple(int arr[], int n) { Â
    // We can always find a valid quadruplet pair     // for array size greater than MAX     if (n >= MAX)         return true; Â
    // For smaller size arrays, perform brute force     for (int i = 0; i < n; i++)         for (int j = i + 1; j < n; j++)             for (int k = j + 1; k < n; k++)                 for (int l = k + 1; l < n; l++)                {                     if ((arr[i] ^ arr[j] ^                          arr[k] ^ arr[l]) == 0)                     {                         return true;                     }                 }     return false; } Â
// Driver codepublic static void main (String[] args) Â Â Â Â Â Â Â Â Â Â Â Â Â Â throws java.lang.Exception{Â Â Â Â int arr[] = { 1, 0, 2, 3, 7 }; Â Â Â Â int n = arr.length;Â
    if (validQuadruple(arr, n))         System.out.println("Yes");     else        System.out.println("No"); }}Â
// This code is contributed by nidhiva |
Python3
# Python3 implementation of the approachMAX = 130Â
# Function that returns true if the array# contains a valid quadruplet pairdef validQuadruple(arr, n):Â
    # We can always find a valid quadruplet pair    # for array size greater than MAX    if (n >= MAX):        return TrueÂ
    # For smaller size arrays,     # perform brute force    for i in range(n):        for j in range(i + 1, n):            for k in range(j + 1, n):                for l in range(k + 1, n):                    if ((arr[i] ^ arr[j] ^                          arr[k] ^ arr[l]) == 0):                        return TrueÂ
    return FalseÂ
# Driver codearr = [1, 0, 2, 3, 7]n = len(arr)Â
if (validQuadruple(arr, n)):Â Â Â Â print("Yes")else:Â Â Â Â print("No")Â
#Â This code is contributed# by Mohit Kumar |
C#
// C# implementation of the approachusing System;Â Â Â Â Â class GFG{Â
static int MAX = 130; Â
// Function that returns true if the array // contains a valid quadruplet pair static Boolean validQuadruple(int []arr, int n) { Â
    // We can always find a valid quadruplet pair     // for array size greater than MAX     if (n >= MAX)         return true; Â
    // For smaller size arrays, perform brute force     for (int i = 0; i < n; i++)         for (int j = i + 1; j < n; j++)             for (int k = j + 1; k < n; k++)                 for (int l = k + 1; l < n; l++)                {                     if ((arr[i] ^ arr[j] ^                          arr[k] ^ arr[l]) == 0)                     {                         return true;                     }                 }     return false; } Â
// Driver codepublic static void Main (String[] args){Â Â Â Â int []arr = { 1, 0, 2, 3, 7 }; Â Â Â Â int n = arr.Length;Â
    if (validQuadruple(arr, n))         Console.WriteLine("Yes");     else        Console.WriteLine("No"); }}Â
// This code is contributed by 29AjayKumar |
PHP
<?php// PHP implementation of the approach const MAX = 130; Â
// Function that returns true if the array // contains a valid quadruplet pair function validQuadruple($arr, $n) { Â
    // We can always find a valid quadruplet pair     // for array size greater than MAX     if ($n >= MAX)         return true; Â
    // For smaller size arrays,    // perform brute force     for ($i = 0; $i < $n; $i++)         for ($j = $i + 1; $j < $n; $j++)             for ($k = $j + 1; $k < $n; $k++)                 for ($l = $k + 1; $l < $n; $l++)                 {                     if (($arr[$i] ^ $arr[$j] ^                          $arr[$k] ^ $arr[$l]) == 0)                     {                         return true;                     }                 }     return false; } Â
// Driver code $arr = array(1, 0, 2, 3, 7); $n = count($arr); Â
if (validQuadruple($arr, $n))     echo ("Yes"); else    echo ("No"); Â
// This code is contributed by Naman_Garg?> |
Javascript
<script>Â
// Javascript implementation // of the approachÂ
const MAX = 130;Â
// Function that returns true if the array// contains a valid quadruplet pairfunction validQuadruple(arr, n){Â
    // We can always find a valid quadruplet pair    // for array size greater than MAX    if (n >= MAX)        return true;Â
    // For smaller size arrays, perform brute force    for (let i = 0; i < n; i++)        for (let j = i + 1; j < n; j++)            for (let k = j + 1; k < n; k++)                for (let l = k + 1; l < n; l++) {                    if ((arr[i] ^ arr[j] ^ arr[k] ^                          arr[l]) == 0) {                        return true;                    }                }    return false;}Â
// Driver code    let arr = [ 1, 0, 2, 3, 7 ];    let n = arr.length;Â
    if (validQuadruple(arr, n))        document.write("Yes");    else        document.write("No");Â
</script> |
Yes
Â
- Time Complexity:Â
Â
- Auxiliary Space: O(1)
- Another Efficient Approach (O(N2log N), for N ≤ 130):Â
Compute Xor of all pairs and hash it. ie, store indexes i and j in a list and Hash it in form <xor, list>. If the same xor is found again for different i and j, then we have a Quadruplet pair.Â
Below is the implementation of the above approach :
Â
C++
//C++ implementation of the approach#include <bits/stdc++.h> using namespace std; Â
bool check(int arr[], int n) { Â Â Â Â if (n < 4) Â Â Â Â Â Â Â Â return false; Â Â Â Â if (n >= 130) Â Â Â Â Â Â Â Â return true; Â Â Â Â Â Â Â Â Â map<int, vector<int> > map; Â
    for (int i = 0; i < n - 1; i++) {         for (int j = i + 1; j < n; j++) {             int k = arr[i] ^ arr[j];             if (map.find(k) == map.end())                 map[k] = { i, j };             else {                 vector<int> data = map[k];                 if (find(data.begin(), data.end(), i) == data.end() &&                     find(data.begin(), data.end(), j) == data.end()) {                     data.push_back(i);                     data.push_back(j);                     if (data.size() >= 4)                         return true;                     map[k] = data;                 }             }         }     }     return false; } Â
// Driver code int main() {     int arr[] = { 1, 0, 2, 3, 7 };     int n = sizeof(arr) / sizeof(arr[0]);     if (check(arr, n))         cout << "Yes";     else        cout << "No";     return 0; } |
Java
// Java implementation of the approachimport java.util.HashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;Â
public class QuadrapuleXor {Â
    static boolean check(int arr[])    {        int n = arr.length;                 if(n < 4)            return false;        if(n >=130)            return true;                     Map<Integer,List<Integer>> map = new HashMap<>();                 for(int i=0;i<n-1;i++)        {               for(int j=i+1;j<n;j++)            {                int k = arr[i] ^ arr[j];                if(!map.containsKey(k))                    map.put(k,new LinkedList<>());                                 List<Integer> data = map.get(k);                if(!data.contains(i) && !data.contains(j))                {                    data.add(i);                    data.add(j);                    if(data.size()>=4)                        return true;                    map.put(k, data);                }            }           }        return false;    }         // Driver code    public static void main (String[] args)                   throws java.lang.Exception    {        int arr[] = { 1, 0, 2, 3, 7 };               if (check(arr))             System.out.println("Yes");         else            System.out.println("No");     }}Â
//This code contributed by Pramod Hosahalli |
Python3
# Python3 implementation of the approachdef check(arr):Â
    n = len(arr)         # if n is less than 4, no quadruplet    # can be possibly formed    if(n < 4):        return False    # if n >= 130, there is guaranteed    # to be a quadruplet    if(n >=130):        return True                  # initializing a dictionary    map = dict()         # building the map    for i in range(n - 1):        for j in range(i + 1, n):            k = arr[i] ^ arr[j]            if k not in map:                map[k] = []            data = map[k]            if i not in data and j not in data:                data.append(i)                data.append(j)                                 # if a quadruplet has been found                # return true                if (len(data) >= 4):                    return True                map[k] = dataÂ
    return FalseÂ
# Driver codearr=[ 1, 0, 2, 3, 7 ]if (check(arr)):Â Â Â Â print("Yes")else:Â Â Â Â print("No")Â
Â
# This code is contributed by phasing17 |
Javascript
<script>// Javascript implementation of the approachÂ
function check(arr){Â Â Â Â let n = arr.length;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if(n < 4)Â Â Â Â Â Â Â Â Â Â Â Â return false;Â Â Â Â Â Â Â Â if(n >=130)Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â let map = new Map();Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â for(let i=0;i<n-1;i++)Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â Â Â for(let j=i+1;j<n;j++)Â Â Â Â Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â let k = arr[i] ^ arr[j];Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if(!map.has(k))Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â map.set(k,[]);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â let data = map.get(k);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if(!data.includes(i) && !data.includes(j))Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â data.push(i);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â data.push(j);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â if(data.length>=4)Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â return true;Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â map.set(k, data);Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return false;}Â
// Driver codelet arr=[ 1, 0, 2, 3, 7 ];if (check(arr))    document.write("Yes<br>");else    document.write("No<br>");Â
Â
// This code is contributed by rag2127</script> |
C#
// C# implementation of the approachusing System;using System.Collections.Generic;Â
public class QuadrapuleXor {Â
  // Function to check whether a quadruplet with XOR 0  // exists in the given array  static bool check(int[] arr)  {    int n = arr.Length;Â
    if (n < 4)      return false;    if (n >= 130)      return true;Â
    Dictionary<int, List<int> > map      = new Dictionary<int, List<int> >();Â
    for (int i = 0; i < n - 1; i++) {      for (int j = i + 1; j < n; j++) {        int k = arr[i] ^ arr[j];        if (!map.ContainsKey(k))          map[k] = new List<int>();Â
        List<int> data = map[k];        if (!data.Contains(i)            && !data.Contains(j)) {          data.Add(i);          data.Add(j);          if (data.Count >= 4)            return true;          map[k] = data;        }      }    }    return false;  }Â
  // Driver code  public static void Main(string[] args)  {    int[] arr = { 1, 0, 2, 3, 7 };Â
    // Function Call    if (check(arr))      Console.WriteLine("Yes");    else      Console.WriteLine("No");  }}Â
// This code is contributed by phasing17 |
Yes
Â
- Time Complexity:
Auxiliary Space: O(N2)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


… [Trackback]
[…] Read More Info here on that Topic: geeksforgeeks.org/quadruplet-pair-with-xor-zero-in-the-given-array/ […]