Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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: 20
Explanation:
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: 12
Explanation: 
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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if all characters
// of the string can be made the same
int sameChar(string S, int N)
{
 
    // Sort the string
    sort(S.begin(), S.end());
 
    // Calculate ASCII value
    // of the median character
    int mid = S[N / 2];
 
    // Stores the minimum number of
    // operations required to make
    // all characters equal
    int total_operations = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
        // Calculate absolute value of
        // current character and median character
        total_operations
            += abs(int(S[i]) - mid);
    }
 
    // Print the minimum number of
    // operations required
    cout << total_operations;
}
 
// Driver Code
int main()
{
    string S = "geeks";
    int N = S.size();
 
    sameChar(S, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.Arrays;
class GFG {
 
  // Function to check if all characters
  // of the string can be made the same
  static void sameChar(String S, int N)
  {
 
    char temp[] = S.toCharArray();
 
    // Sort the string
    Arrays.sort(temp);
 
    String s = new String(temp);
 
    // Calculate ASCII value
    // of the median character
    int mid = s.charAt(N / 2);
 
    // Stores the minimum number of
    // operations required to make
    // all characters equal
    int total_operations = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
      // Calculate absolute value of
      // current character and median character
      total_operations
        += Math.abs(((s.charAt(i) - 0) - mid));
    }
 
    // Print the minimum number of
    // operations required
    System.out.print(total_operations);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    String S = "geeks";
    int N = S.length();
 
    sameChar(S, N);
  }
}
 
// This code is contributed by Dharanendra L V.


Python3




# Python program for the above approach
 
# Function to check if all characters
# of the string can be made the same
def sameChar(S, N):
 
    # Sort the string
    S = ''.join(sorted(S))
 
    # Calculate ASCII value
    # of the median character
    mid = ord(S[N // 2])
 
    # Stores the minimum number of
    # operations required to make
    # all characters equal
    total_operations = 0
 
    # Traverse the string
    for i in range(N):
 
        # Calculate absolute value of
        # current character and median character
        total_operations += abs(ord(S[i]) - mid)
 
    # Print the minimum number of
    # operations required
    print(total_operations)
 
# Driver Code
S = "geeks"
N = len(S)
sameChar(S, N)
 
# This code is contributed by subhammahato348.


C#




// C# program for the above approach
using System;
public class GFG {
 
  // Function to check if all characters
  // of the string can be made the same
  static void sameChar(String S, int N)
  {
 
    char[] temp = S.ToCharArray();
 
    // Sort the string
    Array.Sort(temp);
 
    String s = new String(temp);
 
    // Calculate ASCII value
    // of the median character
    int mid = s[N / 2];
 
    // Stores the minimum number of
    // operations required to make
    // all characters equal
    int total_operations = 0;
 
    // Traverse the string
    for (int i = 0; i < N; i++) {
 
      // Calculate absolute value of
      // current character and median character
      total_operations += Math.Abs((s[i] - 0) - mid);
    }
 
    // Print the minimum number of
    // operations required
    Console.Write(total_operations);
  }
 
  // Driver Code
  static public void Main()
  {
 
    String S = "geeks";
    int N = S.Length;
 
    sameChar(S, N);
  }
}
 
// This code is contributed by Dharanendra L V.


Javascript




<script>
      // JavaScript program for the above approach
      // Function to check if all characters
      // of the string can be made the same
      function sameChar(S, N) {
        // Sort the string
        var arr = S.split("");
        var sorted = arr.sort();
        S = sorted.join("");
 
        // Calculate ASCII value
        // of the median character
        var mid = S[parseInt(N / 2)].charCodeAt(0);
 
        // Stores the minimum number of
        // operations required to make
        // all characters equal
        var total_operations = 0;
 
        // Traverse the string
        for (var i = 0; i < N; i++) {
          // Calculate absolute value of
          // current character and median character
          total_operations += Math.abs(S[i].charCodeAt(0) - mid);
        }
 
        // Print the minimum number of
        // operations required
        document.write(total_operations);
      }
 
      // Driver Code
      var S = "geeks";
      var N = S.length;
      sameChar(S, N);
    </script>


Output

20

Time Complexity: O(N * log(N))
Auxiliary Space: O(1)



Last Updated : 08 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads