VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-operations-for-adjacent-e-and-e1-pairing/

⇱ Minimum operations for adjacent E and E+1 pairing - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum operations for adjacent E and E+1 pairing

Last Updated : 23 Jul, 2025

Given an integer N and an array arr[], containing numbers from 0 to (2*N-1). In one operation you can swap the position of any two integers in the array. Find the minimum number of operations required to make an array in such a format that, each even number 'E' is adjacent to 'E+1' i.e. 0 is adjacent to 1, 2 is adjacent to 3, and so on.

Examples:

Input: N = 2, arr[] = {3, 0, 2, 1}
Output: 1
Explanation: Swap values 0 and 2, after that new array will be {3, 2, 0, 1} where 0 is adjacent to 1 and 2 is adjacent to 3.

Input: N = 3, arr[] = {1, 0, 3, 2, 4, 5}
Output: 0
Explanations: Clearly all even number E is adjacent to E+1.

Approach: We can use Disjoint-Set-Union (DSU) data structure to solve this question efficiently.

Construct a graph where each vertex has two indexes 2i and 2i+1 for each 0 <= i < N. Now we form an edge between two vertices iff the index values of the vertices give 'E' in one vertex and 'E+1' in other vertex, where E is an even number. The total number of vertices - The total number of connected components in the graph will be our answer.

Follow the steps to solve the problem:

  • First, implement the DSU data structure using make(), find(), and Union() functions, and a parent array/map as per need.
  • For each, i from 0 to N, initialize the parent for vertex pair {2i, 2i+1} as itself using the make() function of DSU.
  • Find all the vertex pairs such that one pair has an even 'E' and the other has 'E+1', and combine these vertices using the Union operation of DSU.
  • Find the number of connected components of the DSU, this can be done by finding the unique number of parents existing in the DSU
  • Print (number of vertices - number of connected components) as your answer.

Below is the implementation of the above algorithm.


Output
1

Time Complexity: O(N^2 logN)
Auxiliary Space: O(N)

Comment
Article Tags: