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:
- Initialize the variable min with a large value which will store the minimum answer.
- Traverse over the range [0, 25] where i represent (i + 1)thalphabet from ‘a’ to ‘z’ and perform the following steps:
- Initialize variable cnt initialized as 0 which will store the answer to convert all character of string same.
- Traverse the given string from j = 0 to (N – 1) and add min(abs(i + ‘a’ – S[j]), 26 – abs(i + ‘a’ – S[j])) into cnt.
- After the above step, update min to a minimum of min and cnt.
- After traversing the string for each character, print the value of min as the minimum count of operations.
Below is the implementation of the above approach:
C++
// 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 sameint 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 Codeint main(){ // Given string str string str = "geeksforgeeks"; int N = str.length(); // Function Call cout << minCost(str, N); return 0;} |
Java
// Java program for the above approachimport java.io.*;class GFG{ // Function to find the minimum count// of operations to make all characters// of the String samestatic 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 Codepublic 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
# Python3 program for the # above approach# Function to find the minimum # count of operations to make # all characters of the string samedef 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 Codeif __name__ == "__main__": # Given string str st = "geeksforgeeks" N = len(st) # Function Call print(minCost(st, N))# This code is contributed by Chitranayal |
C#
// C# program for the above approachusing System;class GFG{ // Function to find the minimum count// of operations to make all characters// of the String samestatic 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 codepublic 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 |
60
Time Complexity: O(N * 26)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Minimize replacements or swapping of same indexed characters required to make two given strings palindromic
- Minimize replacement of characters to its nearest alphabet to make a string palindromic
- Minimize the number of replacements to get a string with same number of 'a', 'b' and 'c' in it
- Count of replacements required to make the sum of all Pairs of given type from the Array equal
- Minimum replacements to make adjacent characters unequal in a ternary string
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Minimum replacements in a string to make adjacent characters unequal
- Minimum replacements such that the difference between the index of the same characters is divisible by 3
- Minimize steps required to make all array elements same by adding 1, 2 or 5
- Minimum replacements required to make given Matrix palindromic
- Count characters at same position as in English alphabet
- Min flips of continuous characters to make all characters same in a string
- Minimize characters to be changed to make the left and right rotation of a string same
- Minimum replacements required to obtain a K-periodic palindromic string
- Count minimum character replacements required such that given string satisfies the given conditions
- Minimize difference between maximum and minimum of Array by at most K replacements
- Minimum characters to be replaced to make frequency of all characters same
- Minimum number of replacements to make the binary string alternating | Set 2
- Elements greater than the previous and next element in an Array
- Maximum element in an array such that its previous and next element product is maximum
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.

