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 minimum number of operation required.
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 the arrays i:e for each . If the elements belong to same id then we skip it. Else, we do a Union operation on both elements. At last 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 size of each set to be 1.
Below is the implementation of above approach :
Time Complexity: O(N + n) where N is maximum possible value of an array item and n is number of elements in the array.
- Minimum swaps to make two arrays identical
- Minimum number of changes required to make the given array an AP
- Minimum changes required to make all element in an array equal
- Minimum changes required to make all Array elements Prime
- Find minimum changes required in an array for it to contain k distinct elements
- Minimum array element changes to make its elements 1 to N
- Find the minimum number of preprocess moves required to make two strings equal
- Check whether array has all identical elements using Arrays.asList() and HashSet in Java
- Find side of Square which makes minimal area to fit two identical rectangles inside it
- Count of minimum reductions required to get the required sum K
- Minimum operations required to make all the elements distinct in an array
- Minimum operations required to make all Array elements divisible by K
- Minimum no. of operations required to make all Array Elements Zero
- Minimum array insertions required to make consecutive difference <= K
- Minimum number of cuts required to make circle segments equal sized
- Minimum operations required to make all the array elements equal
- Minimum number of given moves required to make N divisible by 25
- Find the minimum number of operations required to make all array elements equal
- Minimum deletions required to make frequency of each letter unique
- Minimum increment or decrement operations required to make the array sorted
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.