Create an array such that XOR of subarrays of length K is X
Last Updated :
28 Jan, 2022
Given three integers N, K and X, the task is to construct an array of length N, in which XOR of all elements of each contiguous sub-array of length K is X.
Examples:
Input: N = 5, K = 1, X = 4
Output: 4 4 4 4 4
Explanation:
Each subarray of length 1 has Xor value equal to 4.
Input: N = 5, K = 2, X = 4
Output: 4 0 4 0 4
Explanation:
Each subarray of length 2 has Xor value equal to 4.
Approach:
To solve the problem mentioned above, we need to follow the steps given below:
- Bitwise-XOR of any number, X with 0 is equal to the number itself. So, if we set the first element of the array A as X, and the next K – 1 elements as 0, then we will have the XOR of elements of first sub-array of length K, equal to X.
- If we set A[K] as A[0], then we will have XOR(A[1], …, A[K]) = X. Similarly, if we set A[K + 1] as A[1], then we will have XOR(A[2], …, A[K+1]) = X
- Continuing in this manner, we can observe that the general formula can be described as below:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void constructArray( int N, int K, int X)
{
vector< int > ans(K, 0);
ans[0] = X;
for ( int i = 0; i < N; ++i) {
cout << ans[i % K] << " " ;
}
cout << endl;
}
int main()
{
int N = 5, K = 2, X = 4;
constructArray(N, K, X);
return 0;
}
|
Java
class GFG{
public static void constructArray( int N, int K,
int X)
{
int [] ans = new int [K];
ans[ 0 ] = X;
for ( int i = 0 ; i < N; ++i)
{
System.out.print(ans[i % K] + " " );
}
}
public static void main(String[] args)
{
int N = 5 , K = 2 , X = 4 ;
constructArray(N, K, X);
}
}
|
Python3
def constructArray(N, K, X):
ans = []
for i in range ( 0 , K):
ans.append( 0 )
ans[ 0 ] = X
for i in range ( 0 , N):
print (ans[i % K], end = " " )
N = 5
K = 2
X = 4
constructArray(N, K, X)
|
C#
using System;
class GFG{
public static void constructArray( int N, int K,
int X)
{
int [] ans = new int [K];
ans[0] = X;
for ( int i = 0; i < N; ++i)
{
Console.Write(ans[i % K] + " " );
}
}
public static void Main( string [] args)
{
int N = 5, K = 2, X = 4;
constructArray(N, K, X);
}
}
|
Javascript
<script>
function constructArray(N, K, X)
{
let ans = new Array(K).fill(0);
ans[0] = X;
for (let i = 0; i < N; ++i) {
document.write(ans[i % K] + " " );
}
document.write( "<br>" );
}
let N = 5, K = 2, X = 4;
constructArray(N, K, X);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(K)
Share your thoughts in the comments
Please Login to comment...