Open In App

Minimize replacements by previous or next alphabet required to make all characters of a string the same

Given a string S of length N consisting of lowercase alphabets, the task is to find the minimum number of operations required to make all the characters of the string S the same. In each operation, choose any character and replace it with its next or previous alphabet.

Note: The alphabets are considered to be cyclic i.e., Next character of z is considered to be a and previous character of a is considered to be z.



Examples:

Input: S = “abc”
Output: 2
Explanation:
To minimize the number of operation change all characters of the strings to ‘b’.
Operation 1: Change a to b.
Operation 2: Change c to b.



Input: S = “zzza”
Output: 1
Explanation:
To minimize the number of operation change all characters of the strings to ‘z’.
Operation 1: Change a to z.

Approach: To solve the problem, the idea is to calculate the cost of making all the characters equal to each alphabets, ‘a’ to ‘z’, one by one and print the minimum cost required for any of the conversions. Follow the steps below to solve the problem:

Below is the implementation of the above approach:




// C++ program for the above approach
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Function to find the minimum count
// of operations to make all characters
// of the string same
int minCost(string s, int n)
{
 
    // Set min to some large value
    int minValue = 100000000;
 
    // Find minimum operations for
    // each character
    for (int i = 0; i <= 25; i++) {
 
        // Initialize cnt
        int cnt = 0;
 
        for (int j = 0; j < n; j++) {
 
            // Add the value to cnt
            cnt += min(abs(i - (s[j] - 'a')),
                       26 - abs(i - (s[j] - 'a')));
        }
 
        // Update minValue
        minValue = min(minValue, cnt);
    }
 
    // Return minValue
    return minValue;
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "geeksforgeeks";
 
    int N = str.length();
 
    // Function Call
    cout << minCost(str, N);
 
    return 0;
}




// Java program for the above approach
import java.io.*;
 
class GFG{
     
// Function to find the minimum count
// of operations to make all characters
// of the String same
static int minCost(String s, int n)
{
     
    // Set min to some large value
    int minValue = 100000000;
  
    // Find minimum operations for
    // each character
    for(int i = 0; i <= 25; i++)
    {
         
        // Initialize cnt
        int cnt = 0;
  
        for(int j = 0; j < n; j++)
        {
             
            // Add the value to cnt
            cnt += Math.min(Math.abs(i - (s.charAt(j) - 'a')),
                       26 - Math.abs(i - (s.charAt(j) - 'a')));
        }
  
        // Update minValue
        minValue = Math.min(minValue, cnt);
    }
  
    // Return minValue
    return minValue;
}
  
// Driver Code
public static void main (String[] args)
{
     
    // Given String str
    String str = "geeksforgeeks";
  
    int N = str.length();
  
    // Function call
    System.out.println(minCost(str, N));
}
}
 
// This code is contributed by sanjoy_62




# Python3 program for the
# above approach
 
# Function to find the minimum
# count of operations to make
# all characters of the string same
def minCost(s, n):
 
    # Set min to some
    # large value
    minValue = 100000000
 
    # Find minimum operations
    # for each character
    for i in range(26):
 
        # Initialize cnt
        cnt = 0
 
        for j in range(n):
 
            # Add the value to cnt
            cnt += min(abs(i - (ord(s[j]) -
                                ord('a'))),
                       26 - abs(i - (ord(s[j]) -
                                     ord('a'))))
 
        # Update minValue
        minValue = min(minValue, cnt)
 
    # Return minValue
    return minValue
 
# Driver Code
if __name__ == "__main__":
 
    # Given string str
    st = "geeksforgeeks"
 
    N = len(st)
 
    # Function Call
    print(minCost(st, N))
 
# This code is contributed by Chitranayal




// C# program for the above approach
using System;
 
class GFG{
      
// Function to find the minimum count
// of operations to make all characters
// of the String same
static int minCost(string s, int n)
{
     
    // Set min to some large value
    int minValue = 100000000;
   
    // Find minimum operations for
    // each character
    for(int i = 0; i <= 25; i++)
    {
         
        // Initialize cnt
        int cnt = 0;
   
        for(int j = 0; j < n; j++)
        {
              
            // Add the value to cnt
            cnt += Math.Min(Math.Abs(i - (s[j] - 'a')),
                       26 - Math.Abs(i - (s[j] - 'a')));
        }
   
        // Update minValue
        minValue = Math.Min(minValue, cnt);
    }
   
    // Return minValue
    return minValue;
}
   
// Driver code
public static void Main()
{
     
    // Given String str
    string str = "geeksforgeeks";
   
    int N = str.Length;
   
    // Function call
    Console.WriteLine(minCost(str, N));
}
}
 
// This code is contributed by code_hunt




<script>
 
      // JavaScript program for the above approach
 
      // Function to find the minimum count
      // of operations to make all characters
      // of the string same
      function minCost(s, n) {
        // Set min to some large value
        var minValue = 100000000;
 
        // Find minimum operations for
        // each character
        for (var i = 0; i <= 25; i++) {
          // Initialize cnt
          var cnt = 0;
          for (var j = 0; j < n; j++) {
            // Add the value to cnt
            cnt += Math.min(
              Math.abs(i - (s[j].charCodeAt(0) -
              "a".charCodeAt(0))),
              26 - Math.abs(i - (s[j].charCodeAt(0) -
              "a".charCodeAt(0)))
            );
          }
 
          // Update minValue
          minValue = Math.min(minValue, cnt);
        }
 
        // Return minValue
        return minValue;
      }
 
      // Driver Code
       
      // Given string str
      var str = "geeksforgeeks";
      var N = str.length;
       
      // Function Call
      document.write(minCost(str, N));
       
</script>

Output
60

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


Article Tags :