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 }_

Output:_ 2_

Explanation:

Swapping (4, 3) and (5, 6) modifies the array to [2, 3, 4, 1, 6, 5] such that the parity of i and A[i] is same for all indices.

Input:_ A[] = {1, 2, 5, 7}_

Output:_ -1_

Explanation:

The given array cannot be rearranged as per required condition.

Approach:

To solve the problem mentioned above an optimal approach is to choose such an index where parity(i) and parity(A[i]) aren’t same.

  • Initialize two variables needodd and needeven to 0 which will store the parity of each element. Check the parity of index if it’s odd then increase needodd value by 1 otherwise increase needeven.
  • If needodd and needeven aren’t same, then required arrangement is not possible.
  • Otherwise, the final result is obtained by needodd variable, as it is the number of operations that are required. This is because, at any moment, we choose an odd element whose parity is not same with parity of their index and similarly choose an even element and swap them.

#arrays #array-rearrange #swap-program

Minimize swaps to rearrange array such that parity of index
1.30 GEEK