Skip to content
Related Articles

Related Articles

Rearrange given Array such that each element raised to its index is odd

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 23 Feb, 2022
View Discussion
Improve Article
Save Article

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>


 
 

Output

1 2 3 4 5 

 

Time complexity: O(N).
Auxiliary Space: O(N).

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!