# Generate a circular permutation with number of mismatching bits between pairs of adjacent elements exactly 1

Generate a circular permutation with number of mismatching bits between pairs of adjacent elements exactly 1

Given two integers N and S, the task is to find a circular permutation of numbers from the range [0, 2(N – 1)], starting with S such that the count of mismatching bits between any pair of adjacent numbers is one.

Examples:

Input: N = 2, S = 3Output: [3, 2, 0, 1]Explanation: The binary representation of numbers 3, 2, 0 and 1 are “11”, “10”, “01” and “00” respectively.Therefore, arranging them in the order [3, 2, 0, 1] ensures that the number of bit differences between each pair of adjacent elements (circular) is 1.

Input: N = 3, S = 2Output: [2, 6, 7, 5, 4, 0, 1, 3]

Approach: The given problem can be solved based on the following observations:

A simple observation is that the numbers in the range [2i, 2i + 1 – 1] can be obtained in their natural order by placing ‘1’s before each number in the range [0, 2i – 1].

Therefore, the problem can be solved recursively by adding ‘1’ before each number before 2i – 1th index and reverse it before appending the new numbers to permutation.

Follow the steps below to solve the problem:

Initialize a list, say res, to stores the required permutation.

Initialize an integer, say index, to store the position of S in the permutation starting with 0.

Iterate over the range [0, N – 1] and traverse the array res[] in reverse order and check if the sum of the current number and 2i is S or not. If found to be true, then update index with the current index of res and append the current number + 2i in the list res.

Rotate the list res[] by index positions.

After completing the above steps, print the list res[] as the answer.

Below is the implementation of the above approach:

Java

import java.io.*;

import java.util.*;

class GFG {

public static List circularPermutation(

int n, int start)

{

List res = new ArrayList(List.of(0)),

ret = new ArrayList();

int index = -1;

for (int k = 0, add = 1