Given a positive integer N, find a possible arrangement of the integers from 0 to N -1 such that the binary representation of every number (except the first) differs at most at one bit from the binary representation of the number before it. Or tell that it’s impossible to get such an arrangement.

------ Input ------ 

The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first and only line of each test case contains a single integer N.

------ Output ------ 

For every testcase print N integers on a single line, the required sequence. If there are multiple possible answers, print any one.
If no such sequence is possible, print -1.

------ Constraints ------ 

$1 ≤ T ≤ 2000$
$1 ≤ N ≤ 100000$
$1 ≤ sum of N over all test cases ≤ 2000000$

------ Example ------ 

Input:
5
1
2
3
4
5

Output:
0 
0 1 
2 0 1 
0 1 3 2 
4 0 1 3 2 

------ Explanation ------ 

Binary representation of the numbers in the output for N=5 are :
100, 000, 001, 011, and 010.

Source: codechef | Difficulty: VERY_HARD
Tags: Complete search

Bit manipulation

Mathematics

Greedy algorithms


Solutions:
def sol(arr, ct, x):
	while ct <= n - 2:
		for i in range(len(arr)):
			if arr[i] == 0:
				numbr = x + 2 ** i
				if numbr < n and status[numbr] == 0:
					arr[i] = 1
					status[numbr] = 1
					ct += 1
					print(numbr, end=' ')
					x = numbr
					break
			else:
				numbr = x - 2 ** i
				if numbr < n and status[numbr] == 0:
					print(numbr, end=' ')
					arr[i] = 0
					status[numbr] = 1
					ct += 1
					x = numbr
					break
t = int(input())
for j in range(t):
	n = int(input())
	arr = [0] * 32
	x = n - 1
	k = 0
	status = [0] * 100001
	while x > 0:
		arr[k] = x & 1
		x //= 2
		k += 1
	status[n - 1] = 1
	print(n - 1, end=' ')
	sol(arr, 0, n - 1)
	print()