Check if permutation of first N natural numbers exists having Bitwise AND of adjacent elements non-zero
Last Updated :
21 Apr, 2021
Given an integer N, the task is to check if there exists any permutation of the first N natural numbers [1, N] such that Bitwise AND of any pair of consecutive elements is not equal to 0. If any such permutation exists, print “Yes”. Otherwise, print “No”.
Examples:
Input : 5
Output: Yes
Explanation: Permutation {2, 3, 1, 5, 4} satisfies the condition.
Input: 4
Output: No
Explanation: Since Bitwise AND of 4 and 3 is equal to 0, they cannot be placed adjacently. Similarly 2 and 4, 1 and 2, 1 and 4 cannot be placed adjacently. Therefore, no such permutation exists.
Approach: The problem can be solved based on the following observations:
- If N is a power of two, then N & (N – 1) is equal to 0. Therefore, no possible solution exists.
- Otherwise, a permutation exists.
Therefore, to solve the problem, simply check if N is a power of 2 or not. If found to be false, print “Yes“. Otherwise, print “No“.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void check( int n)
{
if ((n & n - 1) != 0)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main()
{
int n = 5;
check(n);
return 0;
}
|
Java
import java.util.*;
class solution{
static void check( int n)
{
if ((n & n - 1 ) != 0 )
System.out.println( "YES" );
else
System.out.println( "NO" );
}
public static void main(String args[])
{
int n = 5 ;
check(n);
}
}
|
Python3
def check(n):
if ((n & n - 1 ) ! = 0 ):
print ( "YES" )
else :
print ( "NO" )
if __name__ = = '__main__' :
n = 5
check(n)
|
C#
using System;
class solution{
static void check( int n)
{
if ((n & n - 1) != 0)
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
public static void Main(String []args)
{
int n = 5;
check(n);
}
}
|
Javascript
<script>
function check(n)
{
if ((n & n - 1) != 0)
document.write( "YES" );
else
document.write( "NO" );
}
var n = 5;
check(n);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...