Python Program To Find Minimum Insertions To Form A Palindrome | DP-28
Last Updated :
23 Jul, 2025
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
Let the input string be str[l……h]. The problem can be broken down into three parts:
- Find the minimum number of insertions in the substring str[l+1,…….h].
- Find the minimum number of insertions in the substring str[l…….h-1].
- 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:
Python 3
# A Naive recursive program to find
# minimum number insertions needed
# to make a string palindrome
import sys
# Recursive function to find
# minimum number of insertions
def findMinInsertions(str, l, h):
# Base Cases
if (l > h):
return sys.maxsize
if (l == h):
return 0
if (l == h - 1):
return 0 if(str[l] == str[h]) else 1
# Check if the first and last characters
# are same. On the basis of the comparison
# result, decide which subproblem(s) to call
if(str[l] == str[h]):
return findMinInsertions(str,
l + 1, h - 1)
else:
return (min(findMinInsertions(str,
l, h - 1),
findMinInsertions(str,
l + 1, h)) + 1)
# Driver Code
if __name__ == "__main__":
str = "geeks"
print(findMinInsertions(str, 0, len(str) - 1))
# This code is contributed by ita_c
Output:
3
Time Complexity: O(2^n), where n is the length of the input string. This is because for each recursive call, there are two possibilities: either we insert a character at the beginning of the string or at the end of the string. Therefore, the total number of recursive calls made is equal to the number of binary strings of length n, which is 2^n.
Memoization based approach(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:
- 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.
- If l is greater than h, then return INT_MAX as this is an invalid case.
- If l is equal to h, then return 0 as no insertions are needed.
- 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.
- If the value of dp[l][h] is not equal to -1, then return the stored value.
- 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.
- 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.
- Return the result stored in the dp[l][h] matrix.
Below is the implementation of the approach:
Python3
# Python3 program to find minimum
# number insertions needed to make a string
# palindrome
# Function to find minimum number
# of insertions
def findMinInsertions(s, dp, l, h):
# Base Cases
if l > h:
return float('inf')
if l == h:
return 0
if l == h - 1:
dp[l][h] = 0 if s[l] == s[h] else 1
return dp[l][h]
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
if s[l] == s[h]:
dp[l][h] = findMinInsertions(s, dp, l + 1, h - 1)
else:
dp[l][h] = min(findMinInsertions(s, dp, l, h - 1),
findMinInsertions(s, dp, l + 1, h)) + 1
return dp[l][h]
# Driver code
if __name__ == "__main__":
s = "geeks"
n = len(s)
# Initialize dp array
dp = [[-1] * n for _ in range(n)]
# Function call
print(findMinInsertions(s, dp, 0, n - 1))
# This code is contributed by Chandramani Kumar
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:
Python3
# A Dynamic Programming based program to
# find minimum number insertions needed
# to make a string palindrome
# A utility function to find minimum
# of two integers
def Min(a, b):
return min(a, b)
# A DP function to find minimum number
# of insertions
def findMinInsertionsDP(str1, n):
# Create a table of size n*n. table[i][j]
# will store minimum number of insertions
# needed to convert str1[i..j] to a
# palindrome.
table = [[0 for i in range(n)]
for i in range(n)]
l, h, gap = 0, 0, 0
# Fill the table
for gap in range(1, n):
l = 0
for h in range(gap, n):
if str1[l] == str1[h]:
table[l][h] = table[l + 1][h - 1]
else:
table[l][h] = (Min(table[l][h - 1],
table[l + 1][h]) + 1)
l += 1
# Return minimum number of insertions
# for str1[0..n-1]
return table[0][n - 1];
# Driver Code
str1 = "geeks"
print(findMinInsertionsDP(str1, len(str1)))
# This code is contributed by Mohit kumar 29
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.
- Find the length of LCS of the input string and its reverse. Let the length be 'l'.
- The minimum number of insertions needed is the length of the input string minus 'l'.
Below is the implementation of the above approach:
Python3
# An LCS based Python3 program to find minimum
# number insertions needed to make a string
# palindrome
""" Returns length of LCS for X[0..m-1],
Y[0..n-1]. See https://www.geeksforgeeks.org/dsa/longest-common-subsequence-dp-4/ for
details of this function """
def lcs(X, Y, m, n) :
L = [[0 for i in range(n + 1)] for j in range(m + 1)]
""" 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 in range(m + 1) :
for j in range(n + 1) :
if (i == 0 or j == 0) :
L[i][j] = 0
elif (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
def findMinInsertionsLCS(Str, n) :
# Using charArray to reverse a String
charArray = list(Str)
charArray.reverse()
revString = "".join(charArray)
# The output is length of string minus
# length of lcs of str and it reverse
return (n - lcs(Str, revString , n, n))
# Driver code
Str = "geeks"
print(findMinInsertionsLCS(Str,len(Str)))
# This code is contributed by divyehrabadiya07
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!
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem