Count of elements which are equal to the XOR of the next two elements
Last Updated :
01 Nov, 2023
Given an array arr[] of n elements. The task is to find the count of elements that are equal to the XOR of the next two elements.
Examples:
Input: arr[] = {4, 2, 1, 3, 7, 8}
Output: 1
2 is the only valid element as 1 ^ 3 = 2
Input: arr[] = {23, 1, 7, 8, 6}
Output: 0
Approach: Initialize count = 0 and for every element of the array such that it has at least two elements appearing after it in the array, if it is equal to the XOR of the next two elements then increment the count.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntElements( int arr[], int n)
{
int cnt = 0;
for ( int i = 0; i < n - 2; i++) {
if (arr[i] == (arr[i + 1] ^ arr[i + 2])) {
cnt++;
}
}
return cnt;
}
int main()
{
int arr[] = { 4, 2, 1, 3, 7, 8 };
int n = sizeof (arr) / sizeof ( int );
cout << cntElements(arr, n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int cntElements( int arr[], int n)
{
int cnt = 0 ;
for ( int i = 0 ; i < n - 2 ; i++)
{
if (arr[i] == (arr[i + 1 ] ^ arr[i + 2 ]))
{
cnt++;
}
}
return cnt;
}
public static void main (String[] args)
{
int arr[] = { 4 , 2 , 1 , 3 , 7 , 8 };
int n = arr.length;
System.out.println (cntElements(arr, n));
}
}
|
Python3
def cntElements(arr, n):
cnt = 0
for i in range (n - 2 ):
if (arr[i] = = (arr[i + 1 ] ^ arr[i + 2 ])):
cnt + = 1
return cnt
arr = [ 4 , 2 , 1 , 3 , 7 , 8 ]
n = len (arr)
print (cntElements(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int cntElements( int []arr, int n)
{
int cnt = 0;
for ( int i = 0; i < n - 2; i++)
{
if (arr[i] == (arr[i + 1] ^ arr[i + 2]))
{
cnt++;
}
}
return cnt;
}
public static void Main (String[] args)
{
int []arr = { 4, 2, 1, 3, 7, 8 };
int n = arr.Length;
Console.WriteLine(cntElements(arr, n));
}
}
|
Javascript
<script>
function cntElements(arr, n)
{
let cnt = 0;
for (let i = 0; i < n - 2; i++) {
if (arr[i] == (arr[i + 1] ^ arr[i + 2]))
{
cnt++;
}
}
return cnt;
}
let arr = [ 4, 2, 1, 3, 7, 8 ];
let n = arr.length;
document.write(cntElements(arr, n));
</script>
|
Time complexity: O(n) where n is no of elements of the given array.
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...