Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Minimum Deletions to Make a String Palindrome
Next article icon

Minimum number of deletions to make a string palindrome | Set 2

Last Updated : 28 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string A, compute the minimum number of characters you need to delete to make resulting string a palindrome.

Examples: 

Input : baca Output : 1  Input : geek Output : 2

We have discussed one approach in below post. 
Minimum number of deletions to make a string palindrome

Below approach will use modified Levenshtein distance. We consider modified Levenshtein (considering only deletions) both original string and its reverse.

C++

// CPP program to find minimum deletions to make
// palindrome.
#include <bits/stdc++.h>
using namespace std;
 
 
int getLevenstein(string const& input)
{
    // Find reverse of input string
    string revInput(input.rbegin(), input.rend());
 
    // Create a DP table for storing edit distance
    // of string and reverse.
    int n = input.size();
    vector<vector<int> > dp(n + 1, vector<int>(n + 1, -1));
    for (int i = 0; i <= n; ++i) {
        dp[0][i] = i;
        dp[i][0] = i;
    }
 
    // Find edit distance between input and revInput
    // considering only delete operation.
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (input[i - 1] == revInput[j - 1])
                dp[i][j] = dp[i - 1][j - 1];           
            else
                dp[i][j] = 1 + min({ dp[i - 1][j], dp[i][j - 1] });           
        }
    }
 
    /*Go from bottom left to top right and find the minimum*/
    int res = numeric_limits<int>::max();
    for (int i = n, j = 0; i >= 0; --i, ++j) {
        res = min(res, dp[i][j]);
        if (i < n)
            res = min(res, dp[i + 1][j]);       
        if (i > 0)
            res = min(res, dp[i - 1][j]);       
    }
    return res;
}
 
// Driver code
int main()
{
    string input("myfirstgeekarticle");
    cout << getLevenstein(input);
    return 0;
}
                      
                       

Java

// Java program to find minimum deletions to make
// palindrome.
import java.io.*;
import java.util.*;
 
class GFG
{
 
    static int getLevenstein(StringBuilder input)
    {
        StringBuilder revInput = new StringBuilder(input);
 
        // Find reverse of input string
        revInput = revInput.reverse();
 
        // Create a DP table for storing edit distance
        // of string and reverse.
        int n = input.length();
        int[][] dp = new int[n + 1][n + 1];
        for (int i = 0; i <= n; ++i)
        {
            dp[0][i] = i;
            dp[i][0] = i;
        }
 
        // Find edit distance between input and revInput
        // considering only delete operation.
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= n; ++j)
            {
                if (input.charAt(i - 1) == revInput.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1];
                else
                    dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
 
        /* Go from bottom left to top right and find the minimum */
        int res = Integer.MAX_VALUE;
        for (int i = n, j = 0; i >= 0; i--, j++)
        {
            res = Math.min(res, dp[i][j]);
            if (i < n)
                res = Math.min(res, dp[i + 1][j]);
            if (i > 0)
                res = Math.min(res, dp[i - 1][j]);
        }
        return res;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        StringBuilder input = new StringBuilder("myfirstgeekarticle");
        System.out.println(getLevenstein(input));
    }
}
 
// This code is contributed by
// sanjeev2552
                      
                       

Python3

# Python3 program to find minimum deletions
# to make palindrome.
INT_MAX = 99999999999
 
def getLevenstein(inpt):
 
    # Find reverse of input string
    revInput = inpt[::-1]
 
    # Create a DP table for storing 
    # edit distance of string and reverse.
    n = len(inpt)
    dp = [[-1 for _ in range(n + 1)]
              for __ in range(n + 1)]
    for i in range(n + 1):
        dp[0][i] = i
        dp[i][0] = i
 
    # Find edit distance between
    # input and revInput considering
    # only delete operation.
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if inpt[i - 1] == revInput[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j],
                                   dp[i][j - 1])
 
    # Go from bottom left to top right
    # and find the minimum
    res = INT_MAX
    i, j = n, 0
    while i >= 0:
        res = min(res, dp[i][j])
        if i < n:
            res = min(res, dp[i + 1][j])
        if i > 0:
            res = min(res, dp[i - 1][j])
        i -= 1
        j += 1
    return res
 
# Driver Code
if __name__ == "__main__":
    inpt = "myfirstgeekarticle"
    print(getLevenstein(inpt))
 
# This code is contributed
# by vibhu4agarwal
                      
                       

C#

// C# program to find minimum deletions to make
// palindrome.
using System;
 
class GFG
{
    static int getLevenstein(String input)
    {
 
        // Find reverse of input string
        String revInput = Reverse(input);
 
        // Create a DP table for storing edit distance
        // of string and reverse.
        int n = input.Length;
        int[,] dp = new int[n + 1, n + 1];
        for (int i = 0; i <= n; ++i)
        {
            dp[0, i] = i;
            dp[i, 0] = i;
        }
 
        // Find edit distance between input and revInput
        // considering only delete operation.
        for (int i = 1; i <= n; ++i)
        {
            for (int j = 1; j <= n; ++j)
            {
                if (input[i - 1] == revInput[j - 1])
                    dp[i, j] = dp[i - 1, j - 1];
                else
                    dp[i, j] = 1 + Math.Min(dp[i - 1, j],
                                            dp[i, j - 1]);
            }
        }
 
        /* Go from bottom left to top right
        and find the minimum */
        int res = int.MaxValue;
        for (int i = n, j = 0; i >= 0; i--, j++)
        {
            res = Math.Min(res, dp[i, j]);
            if (i < n)
                res = Math.Min(res, dp[i + 1, j]);
            if (i > 0)
                res = Math.Min(res, dp[i - 1, j]);
        }
        return res;
    }
    static String Reverse(String input)
    {
        char[] a = input.ToCharArray();
        int l, r = a.Length - 1;
        for (l = 0; l < r; l++, r--)
        {
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return String.Join("",a);
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        String input = "myfirstgeekarticle";
        Console.WriteLine(getLevenstein(input));
    }
}
 
// This code is contributed by 29AjayKumar
                      
                       

Javascript

<script>
// Javascript program to find minimum deletions to make
// palindrome.
function getLevenstein(input)
{
    let revInput = (input).split("");
   
        // Find reverse of input string
        revInput = revInput.reverse();
   
        // Create a DP table for storing edit distance
        // of string and reverse.
        let n = input.length;
        let dp = new Array(n + 1);
        for(let i = 0; i < n + 1; i++)
        {
            dp[i] = new Array(n+1);
            for(let j = 0; j < n + 1; j++)
                dp[i][j] = 0;
        }
        for (let i = 0; i <= n; ++i)
        {
            dp[0][i] = i;
            dp[i][0] = i;
        }
   
        // Find edit distance between input and revInput
        // considering only delete operation.
        for (let i = 1; i <= n; ++i)
        {
            for (let j = 1; j <= n; ++j)
            {
                if (input[i - 1] == revInput[j - 1])
                    dp[i][j] = dp[i - 1][j - 1];
                else
                    dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
            }
        }
   
        /* Go from bottom left to top right and find the minimum */
        let res = Number.MAX_VALUE;
        for (let i = n, j = 0; i >= 0; i--, j++)
        {
            res = Math.min(res, dp[i][j]);
            if (i < n)
                res = Math.min(res, dp[i + 1][j]);
            if (i > 0)
                res = Math.min(res, dp[i - 1][j]);
        }
        return res;
}
 
// Driver Code
let input = ("myfirstgeekarticle");
document.write(getLevenstein(input));
 
// This code is contributed by rag2127
</script>
                      
                       

Output
12

Time complexity: O(<strong> $n^{2}$    </strong>) 
Space complexity: O(<strong> $n^{2}$    </strong>) 

where $n$    is length of string
Why is it working? 
To understand it we need to start from the very beginning of how we create dp[][], for example for word “geek”, it initially looks like this:
\begin{array}{c c c c c c} & null & g & e & e & k\\ null & 0 & 1 & 2 & 3 & 4\\ k & 1 & -1 & -1 & -1 & -1\\ e & 2 & -1 & -1 & -1 & -1\\ e & 3 & -1 & -1 & -1 & -1\\ g & 4 & -1 & -1 & -1 & -1\\ \end{array}

Both 1st row and 1st column are filled with number 1..4 as this is the number of modifications needed to create empty string, i.e: 
[0][1] == 1, to create empty string from letter ‘g’ remove this one letter 
[0][2] == 2, to create empty string from letters “ge”, remove both those letters, etc. 
The same story for first column: 
[1][0] == 1, to create empty string from letter ‘k’ remove this one letter 
[2][0] == 2, to create empty string from letters “ke”, remove both those letters, etc.

Now, we are using dynamic programming approach to get the minimum number of modifications to get every other substring to become second substring, and at the end out dp[][] looks like this:
\begin{array}{c c c c c c} & null & g & e & e & k\\ null & 0 & 1 & 2 & 3 & 4\\ k & 1 & 2 & 3 & 4 & 3\\ e & 2 & 3 & 2 & 3 & 4\\ e & 3 & 4 & 3 & 2 & 3\\ g & 4 & 3 & 4 & 3 & 4\\ \end{array}

So for example minimum number of modifications to get substring ‘gee’ from ‘kee’ is 2. So far so good but this algorithm is doing two things, it is both inserting and deleting characters, and we are only interested in number of removals. So let’s one more time take a look at our resulting array, for example at entry [4][1], this entry states: 
[4][1] – to make string ‘g’ from string “keeg” we need to perform 3 modifications(which is just delete chars “kee”) 
[3][2] – to make string “ge” from “kee” we need to perform 3 modifications also by removing from first string ‘g’ and from second ‘ke’ 
So basically every time we will be moving diagonally up, from left corner we will get number of removals to get the same substring backwards. Thing to notice here is that it is like having on string two pointers, one moving from beginning and other from end. Very important spot is that strings do not necessary has to have even number of characters, so this is the reason we also has to check upper and lower values in dp[][].



Next Article
Minimum Deletions to Make a String Palindrome

M

Mateusz_Wojtczak
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Misc
  • Strings
Practice Tags :
  • Dynamic Programming
  • Misc
  • Strings

Similar Reads

  • Minimum Deletions to Make a String Palindrome
    Given a string s of length 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. Examples : Input : s = "aebcbda"Output : 2Explanation: Remove characters 'e' and 'd'. Resul
    15+ min read
  • Minimum number of Appends needed to make a string palindrome
    Given a string s, the task is to find the minimum characters to be appended (insertion at the end) to make a string palindrome. Examples: Input: s = "abede"Output : 2Explanation: We can make string palindrome as "abedeba" by adding ba at the end of the string.Input: s = "aabb"Output : 2Explanation:
    12 min read
  • Minimum number of characters to be replaced to make a given string Palindrome
    Given string str, the task is to find the minimum number of characters to be replaced to make a given string palindrome. Replacing a character means replacing it with any single character in the same position. We are not allowed to remove or add any characters. If there are multiple answers, print t
    5 min read
  • Number of Counterclockwise shifts to make a string palindrome
    Given a string of lowercase English alphabets, find the number of counterclockwise shifts of characters required to make the string palindrome. It is given that shifting the string will always result in the palindrome. Examples: Input: str = "baabbccb" Output: 2 Shifting the string counterclockwise
    15+ min read
  • Form minimum number of Palindromic Strings from a given string
    Given a string S, the task is to divide the characters of S to form minimum number of palindromic strings. Note: There can be multiple correct answers. Examples: Input: S = "geeksforgeeks"Output: {eegksrskgee, o, f} Explanation: There should be at least 3 strings "eegksrskgee", "o", "f". All 3 forme
    12 min read
  • Minimum moves to make String Palindrome incrementing all characters of Substrings
    Given a string S of length N, the task is to find the minimum number of moves required to make a string palindrome where in each move you can select any substring and increment all the characters of the substring by 1. Examples: Input: S = "264341"Output: 2?Explanation: We can perform the following
    6 min read
  • Minimum number of palindromes required to express N as a sum | Set 2
    Given a number N, we have to find the minimum number of palindromes required to express N as a sum of them. Examples: Input : N = 11 Output : 1 Explanation: 11 is itself a palindrome.Input : N = 65 Output : 3 Explanation: 65 can be expressed as a sum of three palindromes (55, 9, 1). In the previous
    11 min read
  • Count minimum swap to make string palindrome
    Given a string S, the task is to find out the minimum no of adjacent swaps required to make string s palindrome. If it is not possible, then return -1. Examples: Input: aabcb Output: 3 Explanation: After 1st swap: abacb After 2nd swap: abcab After 3rd swap: abcba Input: adbcdbad Output: -1 ApproachT
    6 min read
  • Minimum Count of Bit flips required to make a Binary String Palindromic
    Given an integer N, the task is to find the minimum number of bits required to be flipped to convert the binary representation of N into a palindrome. Examples: Input: N = 12 Output: 2 Explanation: Binary String representing 12 = "1100". To make "1100" a palindrome, convert the string to "0110". The
    7 min read
  • Minimize operations to make String palindrome by incrementing prefix by 1
    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
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences