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

• Last Updated : 29 Apr, 2021

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.

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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++

 `// C++ program for the above approach` `#include ``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;``}`

## Java

 `// 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`

## Python3

 `# 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`

## C#

 `// 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`

## Javascript

 ``

Output:

`3`

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

My Personal Notes arrow_drop_up