VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-changes-required-to-make-two-arrays-identical/

⇱ Minimum changes required to make two arrays identical - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum changes required to make two arrays identical

Last Updated : 11 Jul, 2025

Given two arrays, and with n elements each. The task is to make these two arrays identical i:e, for each , we want to make . In a single operation, you can choose two integers x and y, and replace all the occurrences of x in both the arrays with y. Notice that regardless of the number of occurrences replaced, it will still be counted as a single operation. You have to output the minimum number of operations required.

Examples: 

Input : 1 2 2
 1 2 5
Output: 1
Here, (x, y) = (5, 2) hence ans = 1.

Input : 2 1 1 3 5
 1 2 2 4 5
Output: 2
Here, (x, y) = (1, 2) and (3, 4) thus ans = 2.
Other pairs are also possible.

This problem can be solved with the help of Disjoint Set Union.
We will check all elements of both arrays i:e for each . If the elements belong to the same id then we skip it. Otherwise, we do a Union operation on both elements. Finally, the answer will be the sum of the sizes of all the different disjoint sets formed i:e . We subtract 1 because, initially, we take the size of each set to be 1. 

Implementation:


Output
2

Time Complexity: O(N + n) where N is the maximum possible value of an array item and n is the number of elements in the array.

Comment
Article Tags:
Article Tags: