Find an N-length permutation that contains subarrays with sum less than Bitwise XOR
Last Updated :
08 Jun, 2021
Given a positive integer N, the task is to find a permutation of length N having Bitwise OR of any of its subarray greater than or equal to the length of the subarray.
Examples:
Input: N = 5
Output: 1 3 5 2 4
Explanation:
Consider the subarray {1, 3, 5} from the permutation {1, 3, 5, 2, $}.
Length of the subarray = 3
Bitwise OR of the subarray = 1 | 3 | 5 = 7 ( which is greater than 3)
Similarly, every subarray of any length smaller than equal to N will satisfy the condition.
Input: 4
Output: 4 3 1 2
Approach: Actually any permutation of length N satisfies the required conditions based on the following facts:
- Bitwise OR of any set of numbers is greater than or equal to the maximum number present in that set.
- Since any subarray will contain at least one element greater than or equal to its length, any permutation satisfies the given condition.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void findPermutation( int N)
{
for ( int i = 1; i <= N; i++)
cout << i << " " ;
cout << endl;
}
int main()
{
int N = 5;
findPermutation(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findPermutation( int N)
{
for ( int i = 1 ; i <= N; i++)
System.out.print(i + " " );
}
public static void main(String[] args)
{
int N = 5 ;
findPermutation(N);
}
}
|
Python3
def findPermutation(N):
for i in range ( 1 , N + 1 , 1 ):
print (i, end = " " )
print ( "\n" , end = "")
if __name__ = = '__main__' :
N = 5
findPermutation(N)
|
C#
using System;
class GFG{
static void findPermutation( int N)
{
for ( int i = 1; i <= N; i++)
Console.Write(i + " " );
}
public static void Main()
{
int N = 5;
findPermutation(N);
}
}
|
Javascript
<script>
function findPermutation(N)
{
for ( var i = 1; i <= N; i++)
document.write( i + " " );
document.write( "<br>" );
}
var N = 5;
findPermutation(N);
</script>
|
Time Complexity : O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...