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:
C Program for Longest Palindromic Subsequence | DP-12
Next article icon

C Program To Find Minimum Insertions To Form A Palindrome | DP-28

Last Updated : 14 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.

Before we go further, let us understand with a few examples: 

  • ab: Number of insertions required is 1 i.e. bab
  • aa: Number of insertions required is 0 i.e. aa
  • abcd: Number of insertions required is 3 i.e. dcbabcd
  • abcda: Number of insertions required is 2 i.e. adcbcda which is the same as the number of insertions in the substring bcd(Why?).
  • abcde: Number of insertions required is 4 i.e. edcbabcde
Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

Let the input string be str[l……h]. The problem can be broken down into three parts:  

  1. Find the minimum number of insertions in the substring str[l+1,…….h].
  2. Find the minimum number of insertions in the substring str[l…….h-1].
  3. Find the minimum number of insertions in the substring str[l+1……h-1].

Recursive Approach: The minimum number of insertions in the string str[l…..h] can be given as:  

  • minInsertions(str[l+1…..h-1]) if str[l] is equal to str[h]
  • min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1 otherwise

Below is the implementation of the above approach:  

C
// A Naive recursive program to find minimum  // number insertions needed to make a string // palindrome #include <stdio.h> #include <limits.h> #include <string.h>  // A utility function to find minimum of  // two numbers int min(int a, int b) {  return a < b ? a : b; }  // Recursive function to find minimum number  // of insertions int findMinInsertions(char str[],                        int l, int h) {     // Base Cases     if (l > h)          return INT_MAX;      if (l == h)          return 0;      if (l == h - 1)          return ((str[l] == str[h]) ?                   0 : 1);      // Check if the first and last characters      // are same. On the basis of the comparison      // result, decide which subproblem(s) to call     return (str[l] == str[h])?              findMinInsertions(str, l + 1, h - 1):             (min(findMinInsertions(str, l, h - 1),              findMinInsertions(str, l + 1, h)) + 1); }  // Driver code int main() {     char str[] = "geeks";     printf("%d",      findMinInsertions(str, 0,                        strlen(str)-1));     return 0; } 

Output
3

Memoisation based appraoch(Dynamic Programming):

If we observe the above approach carefully, we can find that it exhibits overlapping subproblems. 
Suppose we want to find the minimum number of insertions in string "abcde":  

                      abcde             /       |                  /        |                    bcde         abcd       bcd  <- case 3 is discarded as str[l] != str[h]        /   |          /   |          /    |         /    |          cde   bcd  cd   bcd abc bc    / |   / |  /| / |  de cd d cd bc c………………….

The substrings in bold show that the recursion is to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.

This gave rise to use dynamic programming approach to store the results of subproblems which can be used later. In this apporach we will go with memoised version and in the next one with tabulation version.

Algorithm:

  1.   Define a function named findMinInsertions which takes a character array str, a two-dimensional vector dp, an integer l   and an integer h as arguments.
  2.   If l is greater than h, then return INT_MAX as this is an invalid case.
  3.   If l is equal to h, then return 0 as no insertions are needed.
  4.   If l is equal to h-1, then check if the characters at index l and h are same. If yes, then return 0 else return 1. Store the           result in the dp[l][h] matrix.
  5.   If the value of dp[l][h] is not equal to -1, then return the stored value.
  6.   Check if the first and last characters of the string str are same. If yes, then call the function findMinInsertions recursively       by passing arguments str, dp, l+1, and h-1.
  7.   If the first and last characters of the string str are not same, then call the function findMinInsertions recursively by               passing arguments str, dp, l, and h-1 and also call the function recursively by passing arguments str, dp, l+1, and h. The     minimum of the two calls is the answer. Add 1 to it, as one insertion is required to make the string palindrome. Store this       result in the dp[l][h] matrix.
  8.   Return the result stored in the dp[l][h] matrix.

Below is the implementation of the approach:

C++
// C++ program to find minimum // number insertions needed to make a string // palindrome  #include <bits/stdc++.h>  using namespace std;  // A utility function to find minimum of // two numbers int min(int a, int b) { return a < b ? a : b; }  // Function to find minimum number // of insertions int findMinInsertions(char str[], vector<vector<int>> &dp,                     int l, int h) {     // Base Cases     if (l > h)         return INT_MAX;      if (l == h)         return 0;      if (l == h - 1)         return dp[l][h] = ((str[l] == str[h]) ?                 0 : 1);        if( dp[l][h] != -1 )           return dp[l][h];        // Check if the first and last characters     // are same. On the basis of the comparison     // result, decide which subproblem(s) to call     return dp[l][h] = (str[l] == str[h])?             findMinInsertions(str, dp, l + 1, h - 1):             (min(findMinInsertions(str, dp, l, h - 1),             findMinInsertions(str, dp, l + 1, h)) + 1); }  // Driver code int main() {     char str[] = "geeks";     int n = strlen(str);          // initialise dp vector      vector<vector<int>> dp(n, vector<int>(n, -1));        printf("%d",     findMinInsertions(str, dp, 0,                     strlen(str)-1));     return 0; }  // This code is contributed by Chandramani Kumar 

Output
3

Time complexity: O(N^2) where N is size of input string.
Auxiliary Space: O(N^2) as 2d dp array has been created to store the states. Here N is size of input string.

Dynamic Programming based Solution: 
If we observe the above approach carefully, we can find that it exhibits overlapping subproblems. 
Suppose we want to find the minimum number of insertions in string "abcde":  

                      abcde             /       |                  /        |                    bcde         abcd       bcd  <- case 3 is discarded as str[l] != str[h]        /   |          /   |          /    |         /    |          cde   bcd  cd   bcd abc bc    / |   / |  /| / |  de cd d cd bc c………………….

The substrings in bold show that the recursion is to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.

How to re-use solutions of subproblems? The memorization technique is used to avoid similar subproblem recalls. We can create a table to store the results of subproblems so that they can be used directly if the same subproblem is encountered again.
The below table represents the stored values for the string abcde. 

a b c d e ---------- 0 1 2 3 4 0 0 1 2 3  0 0 0 1 2  0 0 0 0 1  0 0 0 0 0

How to fill the table? 
The table should be filled in a diagonal fashion. For the string abcde, 0….4, the following should be ordered in which the table is filled:

Gap = 1: (0, 1) (1, 2) (2, 3) (3, 4)  Gap = 2: (0, 2) (1, 3) (2, 4)  Gap = 3: (0, 3) (1, 4)  Gap = 4: (0, 4)

Below is the implementation of the above approach: 

C
// A Dynamic Programming based program to find // minimum number insertions needed to make a // string palindrome #include <stdio.h> #include <string.h>  // A utility function to find minimum of  // two integers int min(int a, int b) {   return a < b ? a : b;  }  // A DP function to find minimum number  // of insertions int findMinInsertionsDP(char str[], int n) {     // Create a table of size n*n. table[i][j]     // will store minimum number of insertions      // needed to convert str[i..j] to a palindrome.     int table[n][n], l, h, gap;      // Initialize all table entries as 0     memset(table, 0, sizeof(table));      // Fill the table     for (gap = 1; gap < n; ++gap)         for (l = 0, h = gap; h < n; ++l, ++h)             table[l][h] = (str[l] == str[h])?                            table[l + 1][h - 1] :                           (min(table[l][h - 1],                             table[l + 1][h]) + 1);      // Return minimum number of insertions      // for str[0..n-1]     return table[0][n-1]; }  // Driver code int main() {     char str[] = "geeks";     printf("%d",      findMinInsertionsDP(str,                          strlen(str)));     return 0; } 

Output
3

Time complexity: O(N^2) 
Auxiliary Space: O(N^2)

Another Dynamic Programming Solution (Variation of Longest Common Subsequence Problem) 
The problem of finding minimum insertions can also be solved using Longest Common Subsequence (LCS) Problem. If we find out the LCS of string and its reverse, we know how many maximum characters can form a palindrome. We need to insert the remaining characters. Following are the steps. 

  1. Find the length of LCS of the input string and its reverse. Let the length be 'l'.
  2. The minimum number of insertions needed is the length of the input string minus 'l'.

Below is the implementation of the above approach:  

C
// An LCS based program to find minimum number // insertions needed to make a string palindrome #include<stdio.h> #include <string.h>  // Utility function to get max of 2 integers  int max(int a, int b) {   return (a > b)? a : b; }  /* Returns length of LCS for X[0..m-1], Y[0..n-1].     See http://goo.gl/bHQVP for details of this     function */ int lcs( char *X, char *Y, int m, int n ) {    int L[m+1][n+1];    int i, j;     /* Following steps build L[m+1][n+1] in bottom        up fashion. Note that L[i][j] contains length       of LCS of X[0..i-1] and Y[0..j-1] */    for (i=0; i<=m; i++)    {      for (j=0; j<=n; j++)      {        if (i == 0 || j == 0)          L[i][j] = 0;         else if (X[i-1] == Y[j-1])          L[i][j] = L[i-1][j-1] + 1;         else          L[i][j] = max(L[i-1][j], L[i][j-1]);      }    }     /* L[m][n] contains length of LCS for        X[0..n-1] and Y[0..m-1] */    return L[m][n]; }  // LCS based function to find minimum number  // of insertions int findMinInsertionsLCS(char str[], int n) {    // Create another string to store reverse     // of 'str'    char rev[n+1];    strcpy(rev, str);    strrev(rev);     // The output is length of string minus length     // of lcs of str and it reverse    return (n - lcs(str, rev, n, n)); }  // Driver code int main() {     char str[] = "geeks";     printf("%d",      findMinInsertionsLCS(str,                           strlen(str)));     return 0; } 

Output: 

3

Time complexity: O(N^2) 
Auxiliary Space: O(N^2) 

Please refer complete article on Minimum insertions to form a palindrome | DP-28 for more details!


Next Article
C Program for Longest Palindromic Subsequence | DP-12
author
kartik
Improve
Article Tags :
  • Strings
  • Dynamic Programming
  • C Programs
  • DSA
  • Amazon
  • Google
  • palindrome
Practice Tags :
  • Amazon
  • Google
  • Dynamic Programming
  • palindrome
  • Strings

Similar Reads

  • C Program To Check If A Linked List Of Strings Forms A Palindrome
    Given a linked list handling string data, check to see whether data is palindrome or not? Examples: Input: a -> bc -> d -> dcb -> a -> NULL Output: True String "abcddcba" is palindrome. Input: a -> bc -> d -> ba -> NULL Output: False String "abcdba" is not palindrome. Reco
    2 min read
  • C Program for Longest Palindromic Subsequence | DP-12
    Given a sequence, find the length of the longest palindromic subsequence in it. As another example, if the given sequence is "BBABCBCAB", then the output should be 7 as "BABCBAB" is the longest palindromic subsequence in it. "BBBBB" and "BBCBB" are also palindromic subsequences of the given sequence
    3 min read
  • Palindrome Number Program in C
    Write a C program to check whether a given number is a palindrome or not. Palindrome numbers are those numbers which after reversing the digits equals the original number. Examples Input: 121Output: YesExplanation: The number 121 remains the same when its digits are reversed. Input: 123Output: NoExp
    4 min read
  • C Program to Check for Palindrome String
    A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. The simplest method to check for palindrome string is to reverse the given string and store it in a tem
    4 min read
  • Check if a string is palindrome in C using pointers
    Given a string. The task is to check if the string is a palindrome or not using pointers. You are not allowed to use any built-in string functions. A string is said to be a palindrome if the reverse of the string is same as the original string. For example, "madam" is palindrome because when the str
    2 min read
  • C++ Program To Find Minimum Insertions To Form A Palindrome | DP-28
    Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Before we go further, let us understand with a few examples: ab: Number of insertions required is 1 i.e. babaa: Number of insertions required is 0 i.e. aaabcd: Number of insertions re
    9 min read
  • Python Program To Find Minimum Insertions To Form A Palindrome | DP-28
    Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Before we go further, let us understand with a few examples: ab: Number of insertions required is 1 i.e. babaa: Number of insertions required is 0 i.e. aaabcd: Number of insertions re
    9 min read
  • Javascript Program To Find Minimum Insertions To Form A Palindrome | DP-28
    Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Before we go further, let us understand with a few examples: ab: Number of insertions required is 1 i.e. babaa: Number of insertions required is 0 i.e. aaabcd: Number of insertions re
    9 min read
  • Minimum insertions to form a palindrome
    Given a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Examples: Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions. Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic str
    15+ min read
  • Minimum insertions to form shortest palindrome
    Given a string S, determine the least number of characters that should be added on to the left side of S so that the complete string becomes a palindrome. Examples: Input: S = "LOL" Output: 0 LOL is already a palindrome Input: S = "JAVA" Output: 3 We need to add 3 characters to form AVAJAVA. The ide
    9 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