Given

###### Example 1:

**Input**: n = 2, start = 3

**Output**: [3,2,0,1]

**Explanation**: The binary representation of the permutation is (11,10,00,01). All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]

###### Example 2:

**Input**:n = 3, start = 2

**Output**: [2,6,7,5,4,0,1,3]

**Explanation**: The binary representation of the permutation is (010,110,111,101,100,000,001,011).

**Constraints:**

#### Solution

Its a problem of generating a Gray code, Only twist we have here is we need to rotate a result list till we get first number as start number.###### Code

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.ArrayList; import java.util.List; public class GrayCode { public static void main(String[] args) { System.out.println(new GrayCode().circularPermutation(3,2)); } public List<Integer> circularPermutation(int a, int start) { List<Integer> result = new ArrayList<Integer>(); if (a == 0) return result; for (int i = 0; i < 1<<a; i++) { result.add(i^i>>>1); //generating a gray code } while (result.get(0) != start) { result.add(result.get(0)); result.remove(0); } return result; } } |

#### Output

We encourage you to write a comment if you have a better solution or having any doubt on the above topic.