Minimize replacement of characters to its nearest alphabet to make a string palindromic

Given a string S of length N consisting of lowercase alphabets, the task is to find the minimum number of operations to convert the given string into a palindrome. In one operation, choose any character and replace it by its next or previous alphabet.

Note: The alphabets are cyclic i.e., if z is incremented then it becomes a and if a is decremented then it becomes z.

Examples:

Input: S = “arcehesmz”
Output: 16
Explanation:
The possible transformation that given the minimum count of operation is: 

  • Decrease 1st character ‘a’ by 1 to get ‘z’. Count of operation = 1
  • Decrease 3rd character ‘c’ by 10 to get ‘s’. Count of operations = 1 + 10 = 11
  • Increase 8th character ‘m’ by 5  to get ‘r’. Count of operations = 11 + 5 = 16.

Therefore, the total count of operations is 16.



Input: S = “abccdb”
Output: 3
Explanation:
The possible transformation that given the minimum count of operation is: 

  • Increase 1st character ‘a’ by 1 to get ‘b’. Count of operation = 1
  • Increase 2nd character ‘b’ by 2 to get ‘d’. Count of operations = 1 + 2 = 3.

Naive Approach: The simplest approach is to generate all possible strings of length N. Then check for each string, if its a palindrome. If any string is found to be palindromic then find the cost of operation required to convert the given string into that string. Repeat the above steps for all the generated strings and print the minimum cost calculated among all the costs. 

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

Efficient Approach: To optimize the above approach, the idea is to traverse the given string and find the change for each position independently. Follow the below steps to solve the problem:

  1. Traverse through the given string over the range [0, (N/2) – 1].
  2. For each character at index i, find the absolute difference between the characters at indices i and (N – i – 1).
  3. There can be two possible differences i.e., the difference when the character at i is incremented to character at index (N – i – 1) and when it is decremented at that index.
  4. Take the minimum of both and add it to the result.
  5. After the above steps, print the minimum cost calculated.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the minimum number
// of operations required to convert
// th given string into palindrome
int minOperations(string s)
{
    int len = s.length();
    int result = 0;
  
    // Iterate till half of the string
    for (int i = 0; i < len / 2; i++) {
  
        // Find the absolute difference
        // between the characters
        int D1 = max(s[i], s[len - 1 - i])
                - min(s[i], s[len - 1 - i]);
  
        int D2 = 26 - D1;
  
        // Adding the minimum difference
        // of the two result
        result += min(D1, D2);
    }
  
    // Return the result
    return result;
}
  
// Driver Code
int main()
{
    // Given string
    string s = "abccdb";
  
    // Function Call
    cout << minOperations(s);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach 
class GFG{
      
// Function to find the minimum number 
// of operations required to convert 
// th given string into palindrome 
public static int minOperations(String s) 
    int len = s.length(); 
    int result = 0
  
    // Iterate till half of the string 
    for(int i = 0; i < len / 2; i++)
    
          
        // Find the absolute difference 
        // between the characters 
        int D1 = Math.max(s.charAt(i),
                          s.charAt(len - 1 - i)) -
                 Math.min(s.charAt(i), 
                          s.charAt(len - 1 - i)); 
  
        int D2 = 26 - D1; 
  
        // Adding the minimum difference 
        // of the two result 
        result += Math.min(D1, D2); 
    
  
    // Return the result 
    return result; 
}
  
// Driver code
public static void main(String[] args) 
{
      
    // Given string 
    String s = "abccdb"
  
    // Function call 
    System.out.println(minOperations(s));
}
}
  
// This code is contributed by divyeshrabadiya07

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach 
  
# Function to find the minimum number
# of operations required to convert
# th given string into palindrome
def minOperations(s):
  
    length = len(s)
    result = 0
  
    # Iterate till half of the string
    for i in range(length // 2):
  
        # Find the absolute difference
        # between the characters
        D1 = (ord(max(s[i], s[length - 1 - i])) -
              ord(min(s[i], s[length - 1 - i])))
          
        D2 = 26 - D1
  
        # Adding the minimum difference
        # of the two result
        result += min(D1, D2)
  
    # Return the result
    return result
  
# Driver Code
  
# Given string 
s = "abccdb"
  
# Function call
print(minOperations(s))
  
# This code is contributed by Shivam Singh

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach 
using System;
  
class GFG{
      
// Function to find the minimum number 
// of operations required to convert 
// th given string into palindrome 
public static int minOperations(String s) 
    int len = s.Length; 
    int result = 0; 
  
    // Iterate till half of the string 
    for(int i = 0; i < len / 2; i++)
    
          
        // Find the absolute difference 
        // between the characters 
        int D1 = Math.Max(s[i],
                          s[len - 1 - i]) -
                 Math.Min(s[i], 
                          s[len - 1 - i]); 
  
        int D2 = 26 - D1; 
  
        // Adding the minimum difference 
        // of the two result 
        result += Math.Min(D1, D2); 
    
  
    // Return the result 
    return result; 
}
  
// Driver code
public static void Main(String[] args) 
{
      
    // Given string 
    String s = "abccdb"
  
    // Function call 
    Console.WriteLine(minOperations(s));
}
}
  
// This code is contributed by Amit Katiyar

chevron_right


Output:

3

Time Complexity: O(N)
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.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

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.