Minimum Insertion Steps to Make a String Palindrome
LeetCode 1437 | Difficulty: Hardβ
HardProblem Descriptionβ
Given a string s. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we do not need any insertions.
Example 2:
Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".
Example 3:
Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".
Constraints:
- `1 <= s.length <= 500`
- `s` consists of lowercase English letters.
Topics: String, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 92 ms)β
| Metric | Value |
|---|---|
| Runtime | 92 ms |
| Memory | 39.1 MB |
| Date | 2021-12-19 |
public class Solution {
public int MinInsertions(string s) {
int n = s.Length;
int[,] dp = new int[n+1, n+1];
for(int i=0;i<n;i++)
{
for (int j = 0; j < n; j++)
{
dp[i+1,j+1] = (s[i] == s[n-1-j]) ? dp[i,j]+1 : Math.Max(dp[i,j+1], dp[i+1,j]);
}
}
return n-dp[n,n];
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| DP (2D) | $O(n Γ m)$ | $O(n Γ m)$ |
Interview Tipsβ
- Break the problem into smaller subproblems. Communicate your approach before coding.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.
- LeetCode provides 2 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: Is dynamic programming suitable for this problem ?
Hint 2: If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.