Generate permutation of [1, N] having bitwise XOR of adjacent differences as 0 Last Updated : 26 Sep, 2022 Summarize Comments Improve Suggest changes Share Like Article Like Report 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[1]− A[2] | ^ | A[2]− A[3] | ^ . . . ^ | A[N −1] − A[N] | = 0, where |X - Y| represents absolute difference between X and Y. Examples: Input: N = 4Output: 2 3 1 4Explanation: |2 -3| ^ |3 -1| ^ |1-4| = 1 ^ 2 ^ 3 = 0 Input: N = 3Output: 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. C++ // C++ implementation of above approach #include <bits/stdc++.h> using namespace std; // Function to print shuffle array vector<int> shuffleArray(int n) { vector<int> res; // Base case if (n < 3) cout << -1 << endl; // When n is odd print array in // increasing order else if (n % 2 != 0) { for (int i = 1; i <= n; i++) res.push_back(i); } // When n is even print first 2 3 1 4 // rest element in increasing order else { res = { 2, 3, 1, 4 }; for (int i = 5; i <= n; i++) res.push_back(i); } return res; } // Driver code int main() { int N = 4; vector<int> ans = shuffleArray(N); for (int x : ans) cout << x << " "; return 0; } Java // Java implementation of above approach import java.util.*; public class GFG { // Function to print shuffle array static ArrayList<Integer> shuffleArray(int n) { ArrayList<Integer> res = new ArrayList<Integer>(); // Base case if (n < 3) System.out.println(-1); // When n is odd print array in // increasing order else if (n % 2 != 0) { for (int i = 1; i <= n; i++) res.add(i); } // When n is even print first 2 3 1 4 // rest element in increasing order else { res.clear(); res.add(2); res.add(3); res.add(1); res.add(4); for (int i = 5; i <= n; i++) res.add(i); } return res; } // Driver code public static void main(String args[]) { int N = 4; ArrayList<Integer> ans = shuffleArray(N); for (int i = 0; i < ans.size(); i++) System.out.print(ans.get(i) + " "); } } // This code is contributed by Samim Hossain Mondal. Python3 # Python3 implementation of above approach # Function to print shuffle array def shuffleArray(n): res = [] # Base case if (n < 3): print(-1) # When n is odd print array in # increasing order elif (n % 2 != 0): for i in range(1, n): res.append(i) # When n is even print first 2 3 1 4 # rest element in increasing order else: res = [2, 3, 1, 4] for i in range(5, n): res.append(i) return res # Driver code if __name__ == '__main__': n = 4 res = shuffleArray(n) for i in res: print(i, end=' ') # This code is contributed by richasalan57. C# // C# implementation of above approach using System; using System.Collections; class GFG { // Function to print shuffle array static ArrayList shuffleArray(int n) { ArrayList res = new ArrayList(); // Base case if (n < 3) Console.WriteLine(-1); // When n is odd print array in // increasing order else if (n % 2 != 0) { for (int i = 1; i <= n; i++) res.Add(i); } // When n is even print first 2 3 1 4 // rest element in increasing order else { res.Clear(); res.Add(2); res.Add(3); res.Add(1); res.Add(4); for (int i = 5; i <= n; i++) res.Add(i); } return res; } // Driver code public static void Main() { int N = 4; ArrayList ans = shuffleArray(N); foreach (int x in ans) Console.Write(x + " "); } } // This code is contributed by Samim Hossain Mondal. JavaScript <script> // JavaScript implementation of above approach // Function to print shuffle array function shuffleArray(n) { let res = []; // Base case if (n < 3) document.write(-1,"</br>"); // When n is odd print array in // increasing order else if (n % 2 != 0) { for (let i = 1; i <= n; i++) res.push(i); } // When n is even print first 2 3 1 4 // rest element in increasing order else { res = [ 2, 3, 1, 4 ]; for (let i = 5; i <= n; i++) res.push(i); } return res; } // Driver code let N = 4; let ans = shuffleArray(N); for(let x of ans) document.write(x," "); // This code is contributed by shinjanpatra </script> Output2 3 1 4 Time Complexity: O(N)Auxiliary space: O(N) because it is using extra space for vector res Comment More infoAdvertise with us Next Article Generate permutation of [1, N] having bitwise XOR of adjacent differences as 0 N nobita04 Follow Improve Article Tags : Pattern Searching Mathematical Geeks Premier League DSA Geeks-Premier-League-2022 permutation Bitwise-XOR +2 More Practice Tags : MathematicalPattern Searchingpermutation Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Like