VOOZH about

URL: https://www.geeksforgeeks.org/dsa/non-repeating-bitwise-or-permutation/

⇱ Non-Repeating Bitwise OR Permutation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Non-Repeating Bitwise OR Permutation

Last Updated : 9 Jan, 2024

Given an integer N (N >= 3). Then the task is to output a permutation such that the bitwise OR of the previous two elements is not equal to the current element, given that the previous two element exists.

Note: If multiple permutation exists, just print any valid permutation.

Examples:

Input: N = 3
Output: 1 3 2
Explanation:

  • First element: A[1] = 1. Two previous elements don't exist. Therefore, no need to check.
  • Second element: A[2] = 3. Two previous elements don't exist. Therefore, no need to check.
  • Third element: A[3] = 2. Two previous elements are 1 and 3. Bitwise OR of 1 and 3 is (1 | 3) = 3, which is not equal to 2.

Thus, permutation satisfies the problem constraints.

Input: N = 5
Output: 2 1 5 3 4
Explanation:

  • First element: A[1] = 2. Two previous elements don't exist. Therefore, no need to check.
  • Second element: A[2] = 1. Two previous elements don't exist. Therefore, no need to check.
  • Third element: A[3] = 5. Two previous elements are 1 and 2. Bitwise OR of 1 and 2 is (1 | 2) = 3, which is not equal to 5.
  • Fourth element: A[4] = 3. Two previous elements are 1 and 5. Bitwise OR of 1 and 5 is (1 | 5) = 5, which is not equal to 3.
  • Fifth element: A[5] = 4. Two previous elements are 5 and 3. Bitwise OR of 5 and 3 is (5 | 3) = 7, which is not equal to 4.

Approach: Implement the idea below to solve the problem

The problem is observation based. It must be noted that if X, Y, Z are positive integers such that Z = (X | Y), Then Z >= max(X, Y). Therefore, If we output N numbers in decreasing order then there's no way our permutation can be wrong. Hence, it's our required answer.

Steps taken to solve the problem:

  • Run a loop reversely from i = N to i = 1 and output i.

Code to implement the approach:


Output
5 4 3 2 1 

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

Comment