Given two integers N and Y, the task is to generate a sequence of N distinct non-negative integers whose bitwise-XOR of all the elements of this generated sequence is equal to Y i.e. A1 ^ A2 ^ A3 ^ ….. ^ AN = Y where ^ denotes bitwise XOR. if no such sequence is possible then print -1.
Input: N = 4, Y = 3
Output: 1 131072 131074 0
(1 ^ 131072 ^ 131074 ^ 0) = 3 and all four elements are distinct.
Input: N = 10, Y = 6
Output: 1 2 3 4 5 6 7 131072 131078 0
Approach: This is a constructive problem and may contain multiple solutions. Follow the below steps to generate the required sequence:
- Take first N – 3 elements as part of the sequence i.e. 1, 2, 3, 4, …, (N – 3)
- Let the XOR of the chosen elements be x and num be an integer which has not been chosen yet. Now there are two cases:
- If x = y then we can add num, num * 2 and (num ^ (num * 2)) to the last 3 remaining numbers because num ^ (num * 2) ^ (num ^ (num * 2)) = 0 and x ^ 0 = x
- If x != y then we can add 0, num and (num ^ x ^ y) because 0 ^ num ^ (num ^ x ^ y) = x ^ y and x ^ x ^ y = y
Note: Sequence is not possible when N = 2 and Y = 0 because this condition can only be satisfied by two equal numbers which is not allowed.
Below is the implementation of the above approach:
1 131072 131074 0
Time Complexity: O(N)
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array
- Maximum sub-sequence sum such that indices of any two adjacent elements differs at least by 3
- Minimum array elements to be changed to make it a Lucas Sequence
- Split the array elements into strictly increasing and decreasing sequence
- Minimum array elements to be changed to make Recaman's sequence
- Find the lexicographically smallest sequence which can be formed by re-arranging elements of second array
- Minimum number of elements to be replaced to make the given array a Fibonacci Sequence
- Find an element in an array such that elements form a strictly decreasing and increasing sequence
- Minimum operations required to transform a sequence of numbers to a sequence where a[i]=a[i+2]
- k-th missing element in increasing sequence which is not present in a given sequence
- Convert an unbalanced bracket sequence to a balanced sequence
- Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements
- Minimum elements to change so that for an index i all elements on the left are -ve and all elements on the right are +ve
- Array of Strings in C++ (3 Different Ways to Create)
- Create linked list from a given 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.