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.
Input: N = 5, K = 1, X = 4
Output: 4 4 4 4 4
Each subarray of length 1 has Xor value equal to 4.
Input: N = 5, K = 2, X = 4
Output: 4 0 4 0 4
Each subarray of length 2 has Xor value equal to 4.
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, then we will have XOR(A, …, A[K]) = X. Similarly, if we set A[K + 1] as A, then we will have XOR(A, …, A[K+1]) = X
- Continuing in this manner, we can observe that the general formula can be described as below:
A[i] = X, when i % K == 0
A[i] = 0, when i % K != 0 where i is in the range [0,N – 1]
Below is the implementation of the above approach:
4 0 4 0 4
Time Complexity: O(N)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count of possible subarrays and subsequences using given length of Array
- Generate a unique Array of length N with sum of all subarrays divisible by N
- Count of Subarrays in an array containing numbers from 1 to the length of subarray
- Maximum length L such that the sum of all subarrays of length L is less than K
- Maximum GCD of all subarrays of length at least 2
- Maximum sum of non-overlapping subarrays of length atmost K
- Make sum of all subarrays of length K equal by only inserting elements
- Count subarrays with non-zero sum in the given Array
- Product of all Subarrays of an Array | Set 2
- Product of all Subarrays of an Array
- Sum of Bitwise-OR of all subarrays of a given Array | Set 2
- Split array in three equal sum subarrays
- Split an array into two equal Sum subarrays
- Find an array of size N having exactly K subarrays with sum S
- Product of all non repeating Subarrays of an Array
- Differences between number of increasing subarrays and decreasing subarrays in k sized windows
- Maximum product of sum of two contiguous subarrays of an array
- Find if array can be divided into two subarrays of equal sum
- Sum of minimum element of all subarrays of a sorted array
- Count subarrays consisting of only 0's and only 1's in a binary array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.