Given a ternary array (every element has one the three possible values 1, 2 and 3). Our task is to replace the minimum number of numbers in it so that all the numbers in the array are equal to each other.
Input : arr = 1 3 2 2 2 1 1 2 3 Output : 5 In this example, frequency of 1 is 3, frequency of 2 is 4 and frequency of 3 is 2. As we can see that 2 is having the more frequency than 1 and 3. So, if we replace all the 1's and 3's by 2 then, the resultant array has all the elements equal to each other in minimum replacements. Here, total no. of 1's and 3's is 5 so it takes 5 replacements to replace them by 2. Hence, the output is 5. Input : arr = 3 3 2 2 1 3 Output : 3 In this example, 3 has the max frequency. Hence, minimum number of replacements are 3 to replace 1 and 2 by 3. Hence, the output is 3.
The approach is to calculate frequency of each element of the given array. Then, the difference of n(no. of elements) and max_frequency(frequency of the element occurs maximum time in the array) will be minimum number of replacements needed.
# Python 3 program minimum number of
# replacements needed to be performed
# to make all the numbers in the given
# array equal.
def minReplacements(arr, n):
# Find the most frequent element
freq =  * 3
for i in range(n):
freq[arr[i] – 1] += 1
max_freq = freq
# Returning count of replacing other
# elements with the most frequent.
return (n – max_freq)
# Driver Code
if __name__ == “__main__”:
arr = [ 1, 3, 2, 2,
2, 1, 1, 2, 3 ]
n = len(arr)
print( minReplacements(arr, n) )
# This code is contributed
# by ChitraNayal
- Minimum array element changes to make its elements 1 to N
- Minimum gcd operations to make all array elements one
- Minimum no. of operations required to make all Array Elements Zero
- Make all array elements equal with minimum cost
- Minimum steps to make all the elements of the array divisible by 4
- Minimum operation to make all elements equal in array
- Minimum delete operations to make all elements of array same
- Minimum number of operations on an array to make all elements 0
- Minimum array elements to be changed to make it a Lucas Sequence
- Minimum array elements to be changed to make Recaman's sequence
- Minimum operations required to make all the array elements equal
- Minimum Bitwise AND operations to make any two array elements equal
- Minimum Bitwise OR operations to make any two array elements equal
- Minimum value of X to make all array elements equal by either decreasing or increasing by X
- Lexicographically smallest permutation with distinct elements using minimum replacements
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.