![]() |
VOOZH | about |
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:
Below is the implementation of the above algorithm.
1
Time Complexity: O(N^2 logN)
Auxiliary Space: O(N)