VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-insertions-to-form-a-palindrome-dp-28/

⇱ Minimum insertions to form a palindrome - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum insertions to form a palindrome

Last Updated : 11 May, 2026

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: 3
Explanation: "skgeegks" is a palindromic string, which requires 3 insertions.

Input: s= "abcd"
Output: 3
Explanation: "abcdcba" is a palindromic string.

Input: s= "aba"
Output: 0
Explanation: Given string is already a palindrome hence no insertions are required.

Using Recursion - O(2^n) Time and O(n) Space

Let minimum number of insertions in the string str[l…..h] be findMinInsertions(str[l…..h]). It can be recursively defined as.

  • if str[l] is equal to str[h], then findMinInsertions(str[l+1…..h-1])
  • Else min(findMinInsertions(str[l…..h-1]), findMinInsertions(str[l+1…..h])) + 1

Output
3

Using Top-Down DP (Memoization) - O(n^2) Time and O(n^2) Space

If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:

1. Optimal Substructure: The minimum number of insertions required to make the substring str[l...h] a palindrome depends on the optimal solutions of its subproblems. If str[l] is equal to str[h] then we call recursive call on l + 1 and h - 1 other we make two recursive call to get optimal answer.

2. Overlapping Subproblems: When using a recursive approach, we notice that certain subproblems are computed multiple times. To avoid this redundancy, we can use memoization by storing the results of already computed subproblems in a 2D array.

The problem involves changing two parameters: l (starting index) and h (ending index). Hence, we need to create a 2D array of size (n x n) to store the results, where n is the length of the string. By using this 2D array, we can efficiently reuse previously computed results and optimize the solution.


Output
3

Using Bottom-Up DP (Tabulation) - O(n^2) Time and O(n^2) Space

The iterative approach for finding the minimum number of insertions needed to make a string palindrome follows a similar concept to the recursive solution but builds the solution in a bottom-up manner using a 2D dynamic programming table.

Base Case:

  • if l == h than dp[l][h] = 0. Where 0 <= l <= n - 1
  • If the substring has two characters (h == l + 1), we check if they are the same. If they are, dp[l][h] = 0, otherwise, dp[l][h] = 1.

Recursive Case:

  • If str[l] == str[h], then dp[l][h] = dp[l+1][h-1].
  • Otherwise, dp[l][h] = min(dp[l+1][h], dp[l][h-1]) + 1. 

Output
3

Using Space Optimized DP – O(n ^ 2) Time and O(n) Space

The idea is to reuse the array in such a way that we store the results for the previous row in the same array while iterating through the columns.


Output
3

Related article: 

Comment