Open In App

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

Last Updated : 08 Feb, 2024
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)



Previous Article
Next Article

Similar Reads

Minimum increments or decrements by D required to make all array elements equal
Given an array arr[] of size N and an integer D, the task is to make all array elements equal by incrementing or decrementing minimum number of array elements by D. If it is not possible to make all the array elements equal, then print -1. Examples : Input: N = 4, d = 2, arr[ ] = {2, 4, 6, 8}Output: 4Explanation: Incrementing arr[0] by D(=2) modifi
7 min read
Minimum increments or decrements by 1 required to make all array elements in AP
Given an array arr[] consisting of N integers, the task is to find the minimum number of increment/decrement by 1 required to be performed on array elements to make all the elements of the given array arr[] in AP. If it is not possible to make the array in AP, then print "-1". Examples: Input: arr[] = {19, 16, 9, 5, 0}Output: 3Explanation:Following
11 min read
Check if all characters of a string can be made equal by increments or decrements
Given a string S consisting of N lowercase alphabets, the task is to check if it is possible to make all characters of the string S equal by incrementing and decrementing any two characters from the given string by 1. If it is possible to make all the characters the same, then print "Yes". Otherwise, print "No". Incrementing or decrementing any cha
5 min read
Minimize cost of increments or decrements such that same indexed elements become multiple of each other
Given two arrays A[] and B[] consisting of N integers, the task is to minimize the total cost of incrementing or decrementing array elements by 1 such that for every ith element, either A[i] is a multiple of B[i] or vice-versa. Examples: Input: A[] = {3, 6, 3}, B[] = {4, 8, 13}Output: 4Explanation:Incrementing A[0] by 1 (3 + 1 = 4) makes it multipl
6 min read
Minimize increments or decrements required to make sum and product of array elements non-zero
Given an array arr[] of N integers, the task is to count the minimum number of increment or decrement operations required on the array such that the sum and product of all the elements of the array arr[] are non-zero. Examples: Input: arr[] = {-1, -1, 0, 0}Output: 2Explanation: Perform the following operations to update the array as:Operation 1: In
6 min read
Find K that requires minimum increments or decrements of array elements to obtain a sequence of increasing powers of K
Given an array consisting of N integers, the task is to find the integer K which requires the minimum number of moves to convert the given array to a sequence of powers of K, i.e. {K0, K1, K2, ......., KN - 1}. In each move, increase or decrease an array element by one. Examples: Input: arr[] = {1, 2, 3}Output: 2Explanation: By incrementing arr[2]
7 min read
Minimum increments or decrements required to convert a sorted array into a power sequence
Given a sorted array arr[] consisting of N positive integers, the task is to minimize the total number of increments or decrements of each array element required to convert the given array into a power sequence of any arbitrary integer X. A sequence is called a power sequence of any integer X, if and only if for every ith element (0 ? i &lt; N), ar
8 min read
Minimum increments or decrements required to signs of prefix sum array elements alternating
Given an array arr[] of N integers, the task is to find the minimum number of increments/decrements of array elements by 1 to make the sign of prefix sum of array alternating. Examples: Input: arr[] = {1, -3, 1, 0}Output: 4Explanation:Following are the operations performed on the given array elements: Incrementing the array element arr[1](= -3) by
8 min read
Minimize subarray increments/decrements required to reduce all array elements to 0
Given an array arr[], select any subarray and apply any one of the below operations on each element of the subarray: Increment by oneDecrement by one The task is to print the minimum number of above-mentioned increment/decrement operations required to reduce all array elements to 0. Examples: Input: arr[] = {1, 3, 4, 1}Output: 4Explanation: Optimal
5 min read
Minimize increments or decrements by 2 to convert given value to a perfect square
Given an integer N, the task is to count the minimum number of times N needs to be incremented or decremented by 2 to convert it to a perfect square. Examples: Input: N = 18Output: 1 Explanation: N - 2 = 16(= 42). Therefore, a single decrement operation is required. Input: N = 15Output: 3 Explanation: N - 2 * 3 = 15 - 6 = 9 (= 32). Therefore, 3 dec
14 min read
Article Tags :
Practice Tags :