Complete-Preparation

šŸŽ‰ One-stop destination for all your technical interview Preparation šŸŽ‰

View the Project on GitHub

Minimum number of deletions to make a string palindrome

Given a string of size ā€˜nā€™. The task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome.

Note: The order of characters should be maintained.

Prerequisite: Longest Palindromic Subsequence

Mark: This Question is also known - Minimun number of insertion to make palindrome

Code

int lcs(int x, int y, string s1, string s2)
{
    int dp[x + 1][y + 1];

    for (int i = 0; i < x + 1; i++)
    {
        for (int j = 0; j < y + 1; j++)
        {
            if (i == 0 || j == 0)
                dp[i][j] = 0;
            else if (s1[i - 1] == s2[j - 1])
                dp[i][j] = 1 + dp[i - 1][j - 1];
            else
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }
    return dp[x][y];
}
int lps(int n, string s)
{
    string s2 = string(s.rbegin(), s.rend()); // copy reverse of s in s2
    return lcs(n, n, s, s2);
}
int minimumNumberOfDeletions(string S)
{
    int len = S.size();
    int lpsLen = lps(len, S);
    return len - lpsLen;
}

Complexity Analysis

References