Skip to content
Related Articles

Related Articles

Permutation of first N natural numbers having product of Bitwise AND of adjacent pairs exceeding 0
  • Last Updated : 07 Apr, 2021
GeeksforGeeks - Summer Carnival Banner

Given a positive integer N, the task is to find the permutation of first N natural numbers such that the product of Bitwise AND(&) of pairs of adjacent elements is greater than 0. If no such permutation is found, then print “Not Possible”.

Examples:

Input: N = 3 
Output: 1 3 2 
Explanation: 
1 & 3 = 1 
3 & 2 = 2 
Product of bitwise AND of adjacent elements = 1 * 2 = 2(>0) 
Therefore, the required output is 1 3 2

Input:
Output: Not Possible 
Explanation: 
Possible permutations of first N(= 2) natural numbers are: { { 1, 2 }, { 2, 1 } } 
1 & 2 = 0 
2 & 1 = 0 
Therefore, the required output is Not Possible.

Naive Approach: The simplest approach to solve this problem is to generate all possible permutations of the first N natural numbers. For every permutation check if the product of bitwise AND of its adjacent elements is greater than 0 or not. If found to be true, then print that permutation. Otherwise, print “Not Possible”



Time Complexity: O(N * N!)
Auxiliary Space: O(1)

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

If N is a power of 2, then the bitwise AND of N with any number less than N must be 0.

If bitwise AND of adjacent elements is equal to 0, then the product of bitwise AND of its adjacent element must be 0.

Follow the steps below to solve the problem:

  • If N is a power of 2, then print “Not Possible”.
  • Initialize an array say, arr[] to store the permutation of first N natural numbers that satisfy the given condition.
  • Iterate over the range [1, N], and update arr[i] = i
  • Update first three elements of the array such that bitwise AND of its adjacent elements must be greater than 0, i.e. arr[1] = 2, arr[2] = 3 and arr[3] = 1
  • Iterate over the range [4, N]. For every ith value, check if i is a power of 2 or not. If found to be true, then swap(arr[i], arr[i+1]).
  • Finally, print the arr[].

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a number
// is a power of 2 or not
bool isPowerOfTwo(int n)
{
    if (n == 0)
        return false;
 
    return (ceil(log2(n))
            == floor(log2(n)));
}
 
// Function to find the permutation of first N
// natural numbers such that the product of
// bitwise AND  of adjacent elements is > 0
void findThePermutation(int N)
{
 
    // Base Case, If N = 1, print 1
    if (N == 1) {
        cout << "1";
        return;
    }
 
    // If N is a power of 2,
    // print "Not Possible"
    if (isPowerOfTwo(N)) {
        cout << "Not Possible";
        return;
    }
 
    // Stores permutation of first N
    // natural numbers that satisfy
    // the condition
    int arr[N + 1];
 
    // Iterate over the range [1, N]
    for (int i = 1; i <= N; i++) {
 
        // Update arr[i]
        arr[i] = i;
    }
 
    // Update arr[1], arr[2] and arr[3]
    arr[1] = 2, arr[2] = 3, arr[3] = 1;
 
    // Iterate over the range [4, N]
    for (int i = 4; i <= N; i++) {
 
        // If i is a power of 2
        if (isPowerOfTwo(i)) {
 
            // Swap adjacent elements
            swap(arr[i], arr[i + 1]);
 
            // Update i
            i++;
        }
    }
 
    // Print the array
    for (int i = 1; i <= N; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    // Input
    int N = 5;
 
    // Function Call
    findThePermutation(N);
 
    return 0;
}

Java




// Java program to implement the above approach
class GFG
{
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
   
        // calculate log2 N indirectly
        // using log() method
        int result = (int)(Math.log(N) / Math.log(2));  
        return result;
    }
     
    // Function to check if a number
    // is a power of 2 or not
    static boolean isPowerOfTwo(int n)
    {
        if (n == 0)
            return false;   
        return Math.ceil(log2(n)) == Math.floor(log2(n));
    }
     
    // Function to find the permutation of first N
    // natural numbers such that the product of
    // bitwise AND  of adjacent elements is > 0
    static void findThePermutation(int N)
    {
     
        // Base Case, If N = 1, print 1
        if (N == 1)
        {
            System.out.print("1");
            return;
        }
     
        // If N is a power of 2,
        // print "Not Possible"
        if (isPowerOfTwo(N) == false)
        {
            System.out.print("Not Possible");
            return;
        }
     
        // Stores permutation of first N
        // natural numbers that satisfy
        // the condition
        int arr[] = new int[N + 1];
     
        // Iterate over the range [1, N]
        for (int i = 1; i <= N; i++)
        {
     
            // Update arr[i]
            arr[i] = i;
        }
     
        // Update arr[1], arr[2] and arr[3]
        arr[1] = 2; arr[2] = 3; arr[3] = 1;  
        int temp;
         
        // Iterate over the range [4, N]
        for (int i = 4; i <= N; i++)
        {
     
            // If i is a power of 2
            if (isPowerOfTwo(i) == true)
            {
     
                // Swap adjacent elements
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp ;
                 
                // Update i
                i++;
            }
        }
     
        // Print the array
        for (int i = 1; i <= N; i++)
            System.out.print(arr[i] + " ");
    }
     
    // Driver Code
    public static void main(String[] args)
    {
       
        // Input
        int N = 5;
     
        // Function Call
        findThePermutation(N);
    }
}
 
// This code is contributed by AnkThon

Python3




# Python3 program to implement
# the above approach
from math import ceil, floor, log2
 
# Function to check if a number
# is a power of 2 or not
def isPowerOfTwo(n):
     
    if (n == 0):
        return False
         
    return (ceil(log2(n)) == floor(log2(n)))
 
# Function to find the permutation of first N
# natural numbers such that the product of
# bitwise AND of adjacent elements is > 0
def findThePermutation(N):
     
    # Base Case, If N = 1, pr1
    if (N == 1):
        print("1")
        return
 
    # If N is a power of 2,
    # print "Not Possible"
    if (isPowerOfTwo(N)):
        print("Not Possible")
        return
 
    # Stores permutation of first N
    # natural numbers that satisfy
    # the condition
    arr = [i for i in range(N + 1)]
 
    # Iterate over the range [1, N]
    for i in range(1, N + 1):
         
        # Update arr[i]
        arr[i] = i
 
    # Update arr[1], arr[2] and arr[3]
    arr[1], arr[2], arr[3] = 2, 3, 1
     
    # Iterate over the range [4, N]
    for i in range(4, N + 1):
         
        # If i is a power of 2
        if (isPowerOfTwo(i)):
             
            # Swap adjacent elements
            arr[i], arr[i + 1] = arr[i + 1], arr[i]
 
            # Update i
            i += 1
 
    # Print the array
    for i in range(1, N + 1):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Input
    N = 5
     
    # Function Call
    findThePermutation(N)
 
# This code is contributed by mohit kumar 29

C#




// C# program to implement the above approach
using System;
class GFG
{
 
    // Function to calculate the
    // log base 2 of an integer
    public static int log2(int N)
    {
   
        // calculate log2 N indirectly
        // using log() method
        int result = (int)(Math.Log(N) / Math.Log(2));  
        return result;
    }
     
    // Function to check if a number
    // is a power of 2 or not
    static bool isPowerOfTwo(int n)
    {
        if (n == 0)
            return false;   
        return Math.Ceiling((double)log2(n)) ==
          Math.Floor((double)log2(n));
    }
     
    // Function to find the permutation of first N
    // natural numbers such that the product of
    // bitwise AND  of adjacent elements is > 0
    static void findThePermutation(int N)
    {
     
        // Base Case, If N = 1, print 1
        if (N == 1)
        {
            Console.Write("1");
            return;
        }
     
        // If N is a power of 2,
        // print "Not Possible"
        if (isPowerOfTwo(N) == false)
        {
            Console.Write("Not Possible");
            return;
        }
     
        // Stores permutation of first N
        // natural numbers that satisfy
        // the condition
        int []arr = new int[N + 1];
     
        // Iterate over the range [1, N]
        for (int i = 1; i <= N; i++)
        {
     
            // Update arr[i]
            arr[i] = i;
        }
     
        // Update arr[1], arr[2] and arr[3]
        arr[1] = 2; arr[2] = 3; arr[3] = 1;  
        int temp;
         
        // Iterate over the range [4, N]
        for (int i = 4; i <= N; i++)
        {
     
            // If i is a power of 2
            if (isPowerOfTwo(i) == true)
            {
     
                // Swap adjacent elements
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp ;
                 
                // Update i
                i++;
            }
        }
     
        // Print the array
        for (int i = 1; i <= N; i++)
            Console.Write(arr[i] + " ");
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
       
        // Input
        int N = 5;
     
        // Function Call
        findThePermutation(N);
    }
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// JavaScript program to implement
// the above approach   
 
   // Function to calculate the
  // log base 2 of an integer
    function log2(N) {
 
        // calculate log2 N indirectly
        // using log() method
        var result = parseInt( (Math.log(N) / Math.log(2)));
        return result;
    }
 
    // Function to check if a number
    // is a power of 2 or not
    function isPowerOfTwo(n) {
        if (n == 0)
            return false;
        return Math.ceil(log2(n)) == Math.floor(log2(n));
    }
 
    // Function to find the permutation of first N
    // natural numbers such that the product of
    // bitwise AND of adjacent elements is > 0
    function findThePermutation(N) {
 
        // Base Case, If N = 1, prvar 1
        if (N == 1) {
            document.write("1");
            return;
        }
 
        // If N is a power of 2,
        // prvar "Not Possible"
        if (isPowerOfTwo(N) == false) {
            document.write("Not Possible");
            return;
        }
 
        // Stores permutation of first N
        // natural numbers that satisfy
        // the condition
        var arr = Array(N + 1).fill(0);
 
        // Iterate over the range [1, N]
        for (i = 1; i <= N; i++) {
 
            // Update arr[i]
            arr[i] = i;
        }
 
        // Update arr[1], arr[2] and arr[3]
        arr[1] = 2;
        arr[2] = 3;
        arr[3] = 1;
        var temp;
 
        // Iterate over the range [4, N]
        for (i = 4; i <= N; i++) {
 
            // If i is a power of 2
            if (isPowerOfTwo(i) == true) {
 
                // Swap adjacent elements
                temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
 
                // Update i
                i++;
            }
        }
 
        // Print the array
        for (i = 1; i <= N; i++)
            document.write(arr[i] + " ");
    }
 
    // Driver Code
     
 
        // Input
        var N = 5;
 
        // Function Call
        findThePermutation(N);
 
// This code is contributed by todaysgaurav
 
</script>
Output: 
2 3 1 5 4

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :