New Start day 4 : 03/10/2020 codechef october long POSAND

 question (source:https://www.codechef.com/OCT20B/problems/POSAND)

Positive AND

A permutation  of is beautiful if  is greater than 0 for every 1i<N . You are given an integer , and your task is to construct a beautiful permutation of length or determine that it's impossible.

Note that a&b denotes the bitwise AND of a and b.

Input:

First line will contain T, number of testcases. Then the testcases follow. Each testcase contains a single line of input, an integer N.

Output:

For each test case output  if there is no suitable permutation of length , otherwise output  integers in a single line which form a beautiful permutation. If there are multiple answers output any of them.

Constraints

  • 1N105
  • The sum of N over all test cases does not exceed 106

Subtasks

  • 50 points : 1N,T9
  • 50 points : Original constraints

Sample Input:

3
4
3
5

Sample Output:

-1
1 3 2
2 3 1 5 4

My logic:

The Bitwise and operator '&' perform and operation on bits of 2 numbers so for example 2&1 =0  and 4&5 =4. we have to make longest sequence such that pi&pi+1 >0.  First, let's discuss where it's not possible. If we are given value of N as a power of 2 for example 2,4,8,16 etc then we cannot find any such number x such that x<N and x&N>0. since MSB or most significant bit increases with power of 2.
So for every N=power of 2 the answer would be -1.

But for any other value. let's say 17. 16&17>0, So we need to form a loop. whenever we reach the power of 2 say y we skip it and bring y+1 so the sequence looks like .... y-1,y+1, y and so on. 
for start 5 digits we use  2,3,1,5,4.
so sequence will start as 2,3,1,5,4,6,7,9,8,10,11,12,13,14,15,17,16 .....

My Code:

Comments

Popular posts from this blog

LeetCode 3Sum

30. Substring with Concatenation of All Words

Lowest common ancestor in a binary Tree