Given an array arr of length N, the task is to rearrange the elements of given array such that for each element, its bitwise XOR with its index is an odd value. If no rearrangement is possible return -1.
Example:
Input: arr[] = {1 2 4 3 5}
Output: 1 2 3 4 5
Explanation: In the above array:
for 1st element: value is 1 and index is 0 -> so 1 ^ 0 = 1, which is odd
for 2nd element: value is 2 and index is 1 -> so 2 ^ 1 = 3, which is odd
for 3rd element: value is 4 and index is 2 -> so 4 ^ 2 = 6, which is even -> rearranging will happen
for 4th element: value is 3 and index is 3 -> so 3 ^ 3 = 0, which is even -> rearranging will happen
for 5th element: value is 5 and index is 4 -> so 5 ^ 4 = 3, which is odd
So if we swap the positions of 4 and 3 as {1, 2, 3, 4, 5},
the XOR of 3^2 will become 1, and XOR of 4^3 will become 7, which are both odd.
Hence {1, 2, 3, 4, 5} is one of the possible rearrangements.
Input: arr[] = {1 2 7 3 5}
Output: -1
Approach: The idea to solve this problem is based on the properties of bitwise XOR operator, that:
- XOR of two odd elements is always even,
- XOR of two even elements is always even, and
- XOR of an odd and an even element is always odd.
So to rearrange the array as required, we will store all the even elements at odd indices, and odd elements at even indices.
Follow the below steps to understand how:
- First count how many odd and even index array have, which will be always n/2 and n-n/2 respectively
- Then Count how many odd and even elements array have
- Store the even and odd elements of the array separately
- Check if rearrangement is possible or not, i.e. the count of even elements is equal to odd indices and vice versa or not.
- If not possible, return -1.
- If the rearrangement is possible, Insert all odd elements at even indices, and even elements at odd indices.
- Return the rearranged array at the end.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector< int > rearrange( int arr[], int n)
{
vector< int > ans;
int i;
int oddIndex = n / 2,
evenIndex = n - oddIndex;
int oddElement = 0, evenElement = 0;
vector< int > odd, even;
for (i = 0; i < n; i++)
if (arr[i] % 2) {
oddElement++;
odd.push_back(arr[i]);
}
else {
evenElement++;
even.push_back(arr[i]);
}
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.push_back(-1);
}
else {
int j = 0, k = 0;
for ( int i = 0; i < n; i++)
if (i % 2)
ans.push_back(even[j++]);
else
ans.push_back(odd[k++]);
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 4, 3, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
vector< int > res = rearrange(arr, n);
for ( auto i : res)
cout << i << " " ;
return 0;
}
|
Java
import java.io.*;
import java.util.ArrayList;
class GFG {
static void rearrange( int arr[], int n)
{
ArrayList<Integer> ans = new ArrayList<>();
int oddIndex = n / 2 , evenIndex = n - oddIndex;
int oddElement = 0 , evenElement = 0 ;
ArrayList<Integer> odd = new ArrayList<>();
ArrayList<Integer> even = new ArrayList<>();
for ( int i = 0 ; i < n; i++)
if (arr[i] % 2 == 1 ) {
oddElement++;
odd.add(arr[i]);
}
else {
evenElement++;
even.add(arr[i]);
}
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.add(- 1 );
}
else {
int j = 0 , k = 0 ;
for ( int i = 0 ; i < n; i++)
if (i % 2 == 1 )
ans.add(even.get(j++));
else
ans.add(odd.get(k++));
}
for ( int i = 0 ; i < ans.size(); i++){
System.out.print(ans.get(i) + " " );
}
}
public static void main (String[] args) {
int [] arr = { 1 , 2 , 4 , 3 , 5 };
int n = arr.length;
rearrange(arr, n);
}
}
|
Python3
def rearrange(arr, n):
ans = []
i = 0
oddIndex = n / / 2
evenIndex = n - oddIndex
oddElement, evenElement = 0 , 0
odd, even = [], []
for i in range ( 0 , n):
if (arr[i] % 2 ):
oddElement + = 1
odd.append(arr[i])
else :
evenElement + = 1
even.append(arr[i])
if (oddElement ! = evenIndex
or oddIndex ! = evenElement):
ans.append( - 1 )
else :
j, k = 0 , 0
for i in range ( 0 , n):
if (i % 2 ):
ans.append(even[j])
j + = 1
else :
ans.append(odd[k])
k + = 1
return ans
if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 3 , 5 ]
n = len (arr)
res = rearrange(arr, n)
for i in res:
print (i, end = " " )
|
C#
using System;
using System.Collections;
class GFG {
static ArrayList rearrange( int [] arr, int n)
{
ArrayList ans = new ArrayList();
int oddIndex = n / 2, evenIndex = n - oddIndex;
int oddElement = 0, evenElement = 0;
ArrayList odd = new ArrayList();
ArrayList even = new ArrayList();
for ( int i = 0; i < n; i++)
if (arr[i] % 2 == 1) {
oddElement++;
odd.Add(arr[i]);
}
else {
evenElement++;
even.Add(arr[i]);
}
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.Add(-1);
}
else {
int j = 0, k = 0;
for ( int i = 0; i < n; i++)
if (i % 2 == 1)
ans.Add(even[j++]);
else
ans.Add(odd[k++]);
}
return ans;
}
public static void Main()
{
int [] arr = { 1, 2, 4, 3, 5 };
int n = arr.Length;
ArrayList res = rearrange(arr, n);
for ( int i = 0; i < res.Count; i++) {
Console.Write(res[i] + " " );
}
}
}
|
Javascript
<script>
function rearrange(arr, n) {
let ans = [];
let i;
let oddIndex = Math.floor(n / 2),
evenIndex = n - oddIndex;
let oddElement = 0, evenElement = 0;
let odd = [], even = [];
for (i = 0; i < n; i++)
if (arr[i] % 2) {
oddElement++;
odd.push(arr[i]);
}
else {
evenElement++;
even.push(arr[i]);
}
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.push_back(-1);
}
else {
let j = 0, k = 0;
for (let i = 0; i < n; i++)
if (i % 2)
ans.push(even[j++]);
else
ans.push(odd[k++]);
}
return ans;
}
let arr = [1, 2, 4, 3, 5];
let n = arr.length;
let res = rearrange(arr, n);
for (let i of res)
document.write(i + " " )
</script>
|
Time complexity: O(N).
Auxiliary Space: O(N).
Approach: Recursive Backtracking
We can solve this problem using recursive backtracking. The basic idea is to generate all possible permutations of the given array, and check if the condition is satisfied for each permutation. We can use a recursive function to generate all permutations.
Steps:
- Define a recursive function permute(arr, l, r) to generate all permutations of the given array. The function takes the array, the left index and the right index as input.
- If l==r, it means we have generated a permutation. Check if the condition is satisfied for this permutation. If yes, print the permutation and return True. Otherwise, return False.
- Otherwise, for each index i from l to r, swap the elements at l and i, and recursively call the function permute(arr, l+1, r). After the recursive call, swap the elements back to restore the original array.
C++
#include <bits/stdc++.h>
using namespace std;
bool permute(vector< int >& arr, int l, int r) {
if (l == r) {
bool flag = true ;
for ( int i = 0; i < arr.size(); i++) {
if ((arr[i] ^ i) % 2 == 0) {
flag = false ;
break ;
}
}
if (flag) {
for ( int i = 0; i < arr.size(); i++)
cout << arr[i] << " " ;
cout << endl;
return true ;
} else {
return false ;
}
} else {
for ( int i = l; i <= r; i++) {
swap(arr[l], arr[i]);
if (permute(arr, l + 1, r))
return true ;
swap(arr[l], arr[i]);
}
return false ;
}
}
int main() {
vector< int > arr = {1, 2, 4, 3, 5};
if (!permute(arr, 0, arr.size() - 1))
cout << "-1" << endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static boolean permute(ArrayList<Integer> arr, int l, int r) {
if (l == r) {
boolean flag = true ;
for ( int i = 0 ; i < arr.size(); i++) {
if ((arr.get(i) ^ i) % 2 == 0 ) {
flag = false ;
break ;
}
}
if (flag) {
for ( int i = 0 ; i < arr.size(); i++)
System.out.print(arr.get(i) + " " );
System.out.println();
return true ;
} else {
return false ;
}
} else {
for ( int i = l; i <= r; i++) {
Collections.swap(arr, l, i);
if (permute(arr, l + 1 , r))
return true ;
Collections.swap(arr, l, i);
}
return false ;
}
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList( 1 , 2 , 4 , 3 , 5 ));
if (!permute(arr, 0 , arr.size() - 1 ))
System.out.println( "-1" );
}
}
|
Python3
def permute(arr, l, r):
if l = = r:
flag = True
for i in range ( len (arr)):
if (arr[i] ^ i) % 2 = = 0 :
flag = False
break
if flag:
print (arr)
return True
else :
return False
else :
for i in range (l, r + 1 ):
arr[l], arr[i] = arr[i], arr[l]
if permute(arr, l + 1 , r):
return True
arr[l], arr[i] = arr[i], arr[l]
return False
arr = [ 1 , 2 , 4 , 3 , 5 ]
if not permute(arr, 0 , len (arr) - 1 ):
print ( "-1" )
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static bool Permute(List< int > arr, int l, int r)
{
if (l == r)
{
bool flag = true ;
for ( int i = 0; i < arr.Count; i++)
{
if ((arr[i] ^ i) % 2 == 0)
{
flag = false ;
break ;
}
}
if (flag)
{
foreach ( int num in arr)
Console.Write(num + " " );
Console.WriteLine();
return true ;
}
else
{
return false ;
}
}
else
{
for ( int i = l; i <= r; i++)
{
int temp = arr[l];
arr[l] = arr[i];
arr[i] = temp;
if (Permute(arr, l + 1, r))
return true ;
temp = arr[l];
arr[l] = arr[i];
arr[i] = temp;
}
return false ;
}
}
public static void Main( string [] args)
{
List< int > arr = new List< int >( new int [] { 1, 2, 4, 3, 5 });
if (!Permute(arr, 0, arr.Count - 1))
Console.WriteLine( "-1" );
}
}
|
Javascript
function permute(arr, l, r) {
if (l == r) {
let flag = true ;
for (let i = 0; i < arr.length; i++) {
if ((arr[i] ^ i) % 2 == 0) {
flag = false ;
break ;
}
}
if (flag) {
console.log(arr);
return true ;
} else {
return false ;
}
} else {
for (let i = l; i <= r; i++) {
[arr[l], arr[i]] = [arr[i], arr[l]];
if (permute(arr, l + 1, r)) {
return true ;
}
[arr[l], arr[i]] = [arr[i], arr[l]];
}
return false ;
}
}
let arr = [1, 2, 4, 3, 5];
if (!permute(arr, 0, arr.length - 1)) {
console.log( "-1" );
}
|
The time complexity of this approach is O(N!) since we are generating all possible permutations of the array.
The auxiliary space used is O(N) since we are using a single array to store the permutations.