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
- 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
- Find the minimum number of preprocess moves required to make two strings equal
- Minimum flips of odd indexed elements from odd length subarrays to make two given arrays equal
- Count of minimum reductions required to get the required sum K
- Convert to Strictly increasing integer array with minimum changes
- Minimum number of changes such that elements are first Negative and then Positive
- Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
- Reduce the string by removing K consecutive identical characters
- Count how many times the given digital clock shows identical digits
- 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
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.