Rearrange given Array such that each element raised to its index is odd
Last Updated :
24 Aug, 2023
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++
// 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
// 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
# 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#
// 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.
JavaScript
<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>
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) {
// 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;
}
Java
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");
}
}
Python3
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")
C#
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");
}
}
JavaScript
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");
}
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.
Similar Reads
Rearrange given array such that no array element is same as its index
Given an array arr[] consisting of N distinct integers, the task is to rearrange the array such that no element is same as its index ( 1-based indexing ). If multiple solutions exist, print any one of them. Examples: Input: arr[] = {4, 2, 3, 1}Output: 3 1 4 2Explanation: The elements at indices {1,
7 min read
Rearrange an array such that every odd indexed element is greater than it previous
Given an unsorted array, rearrange the array such that the number at the odd index is greater than the number at the previous even index. There may be multiple outputs, we need to print one of them. Note: Indexing is based on an array, so it always starts from 0. Examples: Input : arr[] = {5, 2, 3,
7 min read
Rearrange array such that all even-indexed elements in the Array is even
Given an array arr[], the task is to check if it is possible to rearrange the array in such a way that every even index(1-based indexing) contains an even number. If such a rearrangement is not possible, print "No". Otherwise, print "Yes" and print a possible arrangement Examples: Input: arr[] = {2,
6 min read
Minimize swaps to rearrange array such that parity of index and corresponding element is same
Given an array A[], the task to find minimum swapping operations required to modify the given array A[] such that for every index in the array, parity(i) = parity(A[i]) where parity(x) = x % 2. If it's impossible to obtain such an arrangement, then print -1. Examples: Input: A[] = { 2, 4, 3, 1, 5, 6
6 min read
Rearrange a linked list such that all even and odd positioned nodes are together
Given a linked list, the task is to rearrange the list in such a way that all odd positioned nodes are together and all even positioned nodes are together.Examples: Input: 1 -> 2 -> 3 -> 4Output: 1 -> 3 -> 2 -> 4Input: 10 -> 22 -> 30 -> 43 -> 56 -> 70Output: 10 ->
13 min read
Rearrange an array such that product of every two consecutive elements is a multiple of 4
Given an array arr[] of size N, the task is to rearrange the array elements such that for every index i(1 <= i <= N - 1), the product of arr[i] and arr[i - 1] is a multiple of 4.Example: Input: arr[] = {1, 10, 100} Output: 1, 100, 10 Explanation: 1 * 100 is divisible by 4 100 * 10 is divisible
11 min read
Rearrange Array to minimize difference of sum of squares of odd and even index elements
Given an array arr[] of size N (multiple of 8) where the values in the array will be in the range [a, (a+8*N) -1] (a can be any positive integer), the task is to rearrange the array in a way such that the difference between the sum of squares at odd indices and sum of squares of the elements at even
15+ min read
Rearrange sorted array such that all odd indices elements comes before all even indices element
Given a sorted array arr[] consisting of N positive integers, the task is to rearrange the array such that all the odd indices elements come before all the even indices elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}Output: 2 4 6 8 1 3 5 7 9 Input: arr[] = {0, 3, 7, 7, 10}Output: 3 7
12 min read
Rearrange array such that even index elements are smaller and odd index elements are greater
Given an array, rearrange the array such that : If index i is even, arr[i] <= arr[i+1]If index i is odd, arr[i] >= arr[i+1] Note: There can be multiple answers. Examples: Input : arr[] = {2, 3, 4, 5} Output : arr[] = {2, 4, 3, 5} Explanation : Elements at even indexes are smaller and elements
10 min read
Rearrange array such that even positioned are greater than odd
Given an array arr[], sort the array according to the following relations: arr[i] >= arr[i - 1], if i is even, â 1 <= i < narr[i] <= arr[i - 1], if i is odd, â 1 <= i < nFind the resultant array.[consider 1-based indexing]Examples: Input: arr[] = [1, 2, 2, 1]Output: [1 2 1 2] Expla
9 min read