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 oddSo 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++ program to Rearrange the array // Such that A[i]^ i is odd #include <bits/stdc++.h> using namespace std;
// Function to rearrange given array vector< int > rearrange( int arr[], int n)
{ vector< int > ans;
int i;
// Count how many odd
// and even index array have
int oddIndex = n / 2,
evenIndex = n - oddIndex;
// Count how many odd
// and even elements array have
int oddElement = 0, evenElement = 0;
// Store the even and odd elements
// of the array separately
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]);
}
// To make XOR of each element
// with its index as odd,
// we have to place each even element
// at an odd index and vice versa
// Therefore check if rearrangement
// is possible or not
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.push_back(-1);
}
// If the rearrangement is possible
else {
// Insert odd elements at even indices
// and even elements at odd indices
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 the rearranged array
return ans;
} // Driver Code 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 program to Rearrange the array // Such that A[i]^ i is odd import java.io.*;
import java.util.ArrayList;
class GFG {
// Function to rearrange given array
static void rearrange( int arr[], int n)
{
ArrayList<Integer> ans = new ArrayList<>();
// Count how many odd
// and even index array have
int oddIndex = n / 2 , evenIndex = n - oddIndex;
// Count how many odd
// and even elements array have
int oddElement = 0 , evenElement = 0 ;
// Store the even and odd elements
// of the array separately
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]);
}
// To make XOR of each element
// with its index as odd,
// we have to place each even element
// at an odd index and vice versa
// Therefore check if rearrangement
// is possible or not
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.add(- 1 );
}
// If the rearrangement is possible
else {
// Insert odd elements at even indices
// and even elements at odd indices
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++));
}
// print the rearranged array
for ( int i = 0 ; i < ans.size(); i++){
System.out.print(ans.get(i) + " " );
}
}
// Driver Code
public static void main (String[] args) {
int [] arr = { 1 , 2 , 4 , 3 , 5 };
int n = arr.length;
rearrange(arr, n);
}
} // This code is contributed by hrithikgarg03188. |
# python3 program to Rearrange the array # Such that A[i]^ i is odd # Function to rearrange given array def rearrange(arr, n):
ans = []
i = 0
# Count how many odd
# and even index array have
oddIndex = n / / 2
evenIndex = n - oddIndex
# Count how many odd
# and even elements array have
oddElement, evenElement = 0 , 0
# Store the even and odd elements
# of the array separately
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])
# To make XOR of each element
# with its index as odd,
# we have to place each even element
# at an odd index and vice versa
# Therefore check if rearrangement
# is possible or not
if (oddElement ! = evenIndex
or oddIndex ! = evenElement):
ans.append( - 1 )
# If the rearrangement is possible
else :
# Insert odd elements at even indices
# and even elements at odd indices
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 the rearranged array
return ans
# Driver Code if __name__ = = "__main__" :
arr = [ 1 , 2 , 4 , 3 , 5 ]
n = len (arr)
res = rearrange(arr, n)
for i in res:
print (i, end = " " )
# This code is contributed by rakeshsahni
|
// C# program to Rearrange the array // Such that A[i]^ i is odd using System;
using System.Collections;
class GFG {
// Function to rearrange given array
static ArrayList rearrange( int [] arr, int n)
{
ArrayList ans = new ArrayList();
// Count how many odd
// and even index array have
int oddIndex = n / 2, evenIndex = n - oddIndex;
// Count how many odd
// and even elements array have
int oddElement = 0, evenElement = 0;
// Store the even and odd elements
// of the array separately
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]);
}
// To make XOR of each element
// with its index as odd,
// we have to place each even element
// at an odd index and vice versa
// Therefore check if rearrangement
// is possible or not
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.Add(-1);
}
// If the rearrangement is possible
else {
// Insert odd elements at even indices
// and even elements at odd indices
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 the rearranged array
return ans;
}
// Driver Code
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] + " " );
}
}
} // This code is contributed by Samim Hossain Mondal. |
<script> // JavaScript code for the above approach
// Function to rearrange given array
function rearrange(arr, n) {
let ans = [];
let i;
// Count how many odd
// and even index array have
let oddIndex = Math.floor(n / 2),
evenIndex = n - oddIndex;
// Count how many odd
// and even elements array have
let oddElement = 0, evenElement = 0;
// Store the even and odd elements
// of the array separately
let odd = [], even = [];
for (i = 0; i < n; i++)
if (arr[i] % 2) {
oddElement++;
odd.push(arr[i]);
}
else {
evenElement++;
even.push(arr[i]);
}
// To make XOR of each element
// with its index as odd,
// we have to place each even element
// at an odd index and vice versa
// Therefore check if rearrangement
// is possible or not
if (oddElement != evenIndex
|| oddIndex != evenElement) {
ans.push_back(-1);
}
// If the rearrangement is possible
else {
// Insert odd elements at even indices
// and even elements at odd indices
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 the rearranged array
return ans;
}
// Driver Code
let arr = [1, 2, 4, 3, 5];
let n = arr.length;
let res = rearrange(arr, n);
for (let i of res)
document.write(i + " " )
// This code is contributed by Potta Lokesh
</script>
|
1 2 3 4 5
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.
#include <bits/stdc++.h> using namespace std;
bool permute(vector< int >& arr, int l, int r) {
if (l == r) {
// check if condition is satisfied
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 elements at index l and i
swap(arr[l], arr[i]);
// recursive call
if (permute(arr, l + 1, r))
return true ;
// restore original array
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;
} |
import java.util.*;
public class GFG {
public static boolean permute(ArrayList<Integer> arr, int l, int r) {
if (l == r) {
// check if condition is satisfied
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++) {
// swap elements at index l and i
Collections.swap(arr, l, i);
// recursive call
if (permute(arr, l + 1 , r))
return true ;
// restore original array
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" );
}
} |
def permute(arr, l, r):
if l = = r:
# check if condition is satisfied
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 ):
# swap elements at index l and i
arr[l], arr[i] = arr[i], arr[l]
# recursive call
if permute(arr, l + 1 , r):
return True
# restore original array
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" )
|
using System;
using System.Collections.Generic;
public class GFG
{ public static bool Permute(List< int > arr, int l, int r)
{
if (l == r)
{
// check if condition is satisfied
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++)
{
// swap elements at index l and i
int temp = arr[l];
arr[l] = arr[i];
arr[i] = temp;
// recursive call
if (Permute(arr, l + 1, r))
return true ;
// restore original array
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" );
}
} |
function permute(arr, l, r) {
if (l == r) {
// Check if condition is satisfied
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++) {
// Swap elements at index l and i
[arr[l], arr[i]] = [arr[i], arr[l]];
// Recursive call
if (permute(arr, l + 1, r)) {
return true ;
}
// Restore original array
[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" );
} |
[1, 2, 3, 4, 5]
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.