Open In App

Minimize operations to make String palindrome by incrementing prefix by 1

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S of numbers of length N, the task is to find the minimum number of operations required to change a string into palindrome and we can perform the following procedure on the string :

  • Choose an index i (0 ? i < N) and for all 0 ? j ? i, set Sj = Sj + 1 (i.e. add 1 to every element in the prefix of length i).

Note: If it is impossible to convert S to a palindrome, print ?1.

Examples:

Input: S = “1234”
Output: 3
?Explanation: We can perform the following operations:
Select i=1, “1234”?”2234″
Select i=2, “2234”?”3334″
Select i=1, “3334”?”4334″ 
Hence 3 number of operations required to change a string into palindrome.

Input:  S = “2442”
?Output: 0
Explanation: The string is already a palindrome.

Approach: The problem can be solved based on the following observation: 

Initially check if the string is already a palindrome or not. If it is not a palindrome, then it can be converted into a palindrome only if all the elements in the right half of the string is greater than the ones in the left half and the difference between the characters closer to end is greater or equal to the difference between the ones closer to the centre.

Follow the steps mentioned below to implement the idea:

  • First set i = 0, j = N -1 and max = IntegerMaximumValue and ans = 0.
  • After that iterate a loop until j > i 
    • Check if S[j] < S[i], if it is true then we can’t change the string into palindrome and return -1.
    • Otherwise, take the absolute difference of S[j] and S[i] and compare it with ans to find the maximum between them:
      • If the maximum value is less than the absolute difference of S[j] and S[i], return -1.
      • Otherwise, max is the absolute difference between S[j] and S[i]
  • Return ans which is the minimum number of operations required to change a string into a palindrome.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find minimum operation
// to convert string into palindrome
int minOperation(string str, int n)
{
    int j = n - 1;
    int i = 0;
    int maxi = INT_MAX;
    int ans = 0;
    while (j > i) {
        if (str[j] < str[i]) {
            return -1;
        }
        int k = abs(str[j] - str[i]);
        ans = max(ans, k);
        if (maxi < k) {
            return -1;
        }
        maxi = k;
        i++;
        j--;
    }
    return ans;
}
 
// Driver Code
int main()
{
    string S = "1234";
    int N = S.length();
 
    // Function call
 
    cout << minOperation(S, N);
    return 0;
}
 
// This code is contributed by aarohirai2616.


Java




// Java code to implement the approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find minimum operation
    // to convert string into palindrome
    public static int minOperation(String str, int n)
    {
        int j = n - 1;
        int i = 0;
        int max = Integer.MAX_VALUE;
        int ans = 0;
        while (j > i) {
            if (str.charAt(j) < str.charAt(i)) {
                return -1;
            }
            int k = Math.abs(str.charAt(j) - str.charAt(i));
            ans = Math.max(ans, k);
            if (max < k) {
                return -1;
            }
            max = k;
            i++;
            j--;
        }
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String S = "1234";
        int N = S.length();
 
        // Function call
        System.out.println(minOperation(S, N));
    }
}


Python3




# Python code to implement the approach
import math
 
# Function to find minimum operation
# to convert string into palindrome
def minOperation(str, n):
 
    j = n - 1
    i = 0
    maxi = 99999999
    ans = 0
    while (j > i):
        if (str[j] < str[i]):
            return -1
 
        k =abs(ord(str[j]) - ord(str[i]))
        ans = max(ans, k)
        if (maxi < k):
            return -1
 
        maxi = k
        i = i + 1
        j = j - 1
 
    return ans
 
# Driver Code
S = "1234"
N = len(S)
print(minOperation(S, N))
 
# This code is contributed by Potta Lokesh.


C#




using System;
class GFG {
    // Function to find minimum operation
    // to convert string into palindrome
    static int minOperation(string str, int n)
    {
        int j = n - 1;
        int i = 0;
        int maxi = Int32.MaxValue;
        int ans = 0;
        while (j > i) {
            if (str[j] < str[i]) {
                return -1;
            }
            int k = Math.Abs(str[j] - str[i]);
            ans = Math.Max(ans, k);
            if (maxi < k) {
                return -1;
            }
            maxi = k;
            i++;
            j--;
        }
        return ans;
    }
    // Driver Code
    static void Main()
    {
        string S = "1234";
        int N = 4;
        // Function Call
        Console.Write(minOperation(S, N));
    }
}


Javascript




// Javascript code to implement the approach
 
// Function to find minimum operation
// to convert string into palindrome
function minOperation( str, n)
{
    let j = n - 1;
    let i = 0;
    let maxi = Number.MAX_VALUE;
    let ans = 0;
    while (j > i) {
        if (str[j] < str[i]) {
            return -1;
        }
        let k = Math.abs(str[j] - str[i]);
        ans = Math.max(ans, k);
        if (maxi < k) {
            return -1;
        }
        maxi = k;
        i++;
        j--;
    }
    return ans;
}
 
// Driver Code
    let S = "1234";
    let N = 4;
 
    // Function call
    console.log(minOperation(S, N));
 
// This code is contributed by garg28harsh.


Output

3

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



Last Updated : 11 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads