Generate permutation of [1, N] having bitwise XOR of adjacent differences as 0
Given an integer N, the task is to generate a permutation from 1 to N such that the bitwise XOR of differences between adjacent elements is 0 i.e., | A− A | ^ | A− A | ^ . . . ^ | A[N −1] − A[N] | = 0, where |X – Y| represents absolute difference between X and Y.
Input: N = 4
Output: 2 3 1 4
Explanation: |2 -3| ^ |3 -1| ^ |1-4| = 1 ^ 2 ^ 3 = 0
Input: N = 3
Output: 1 2 3
Approach: This problem can be solved based on the following observation:
- The XOR of even number of same elements is 0. So if odd number of elements are there (which implies even number of adjacent differences) then arrange them in a way such that the difference between any two adjacent elements is same.
- Else if N is even (which implies odd number of adjacent differences) then arrange the first four in such a way that the XOR of first three differences is 0. Then the remaining elements in the above mentioned away.
Follow the steps mentioned below to implement the above observation:
- If N is odd, arrange all the N elements in a sorted manner because the difference between any two adjacent elements will be 1 and the number of adjacent differences are even.
- If N is even:
- Keep 2, 3, 1, 4 as the first four elements because the 3 differences have XOR 0.
- Now start from 5 and print the remaining elements in sorted order, which will give the difference as 1 for all the remaining even number of differences.
Below is the implementation of the above approach.
2 3 1 4
Time Complexity: O(N)
Auxiliary space: O(N) because it is using extra space for vector res
My Personal Notes arrow_drop_up
Please Login to comment...