Tuesday, 19 Oct 2021

# Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters

Make all characters of a string same by minimum number of increments or decrements of ASCII values of characters
Given a string S of length N, the task is to make all characters of the string the same by incrementing / decrementing the ASCII value of any character by 1 any number of times.Note: All characters must be changed to a character of the original string.
Examples:

Input: S = “geeks”Output: 20Explanation:The minimum number of operations can be attained by making all the characters of the string equal to ‘g’.Increment ASCII value of 2 ‘e’s by 2.Decrement ASCII value of ‘k’ by 4,  Decrement ASCII value of ‘s’ by 12.Hence, the number of operations required = 2 + 2 + 4 + 12 = 20
Input: S = “cake”Output: 12Explanation: The minimum number of operations can be attained by making all the characters of the string equal to ‘c’.Increment ASCII value of ‘a’ by 2.Decrement ASCII value of ‘e’ by 2.Decrement ASCII value of ‘k’ by 8.Hence, number of operations required = 2 + 2 + 8 = 12

Naive approach: The simplest approach to solve the problem is to traverse the string and for each distinct character, calculate the total number of operations required to make all characters of the string the same as that character. Finally, print the minimum number of operations required for any character.Time complexity: O(N2)Auxiliary Space: O(1)Efficient approach: The above approach can be optimized by making an observation that the minimum number of operations can be attained only if the characters are made equal to the median character in a sorted string.Follow the steps below to solve the problem:
Sort characters of the string in non-decreasing order.
Now, to make all characters equal with minimum number of operations, make the characters equal to the character at the middle of the sorted string.
Find the character at the middle of the sorted string as mid = S[N / 2].
Initialize a variable, say total_operations, to store the minimum number of operations required to make all characters of the string equal.
Traverse the string and for each character encountered, update total_operations by adding the absolute difference of current character and mid.
Print total_operations as the minimum number of operations required.
Below is the implementation of the above approach:

C++

#include
using namespace std;

int sameChar(string S, int N)
{

sort(S.begin(), S.end());

int mid = S[N / 2];

int total_operations = 0;

for (int i = 0; i < N; i++) {                              total_operations             += abs(int(S[i]) - mid);     }                  cout