Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"zzazz"
Example 2
"mbadm"
Example 3
"leetcode"
Related Problems
Minimum Number of Moves to Make Palindrome (minimum-number-of-moves-to-make-palindrome)
Step 02
Core Insight
What unlocks the optimal approach
Is dynamic programming suitable for this problem ?
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.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1312: Minimum Insertion Steps to Make a String Palindrome
class Solution {
private Integer[][] f;
private String s;
public int minInsertions(String s) {
this.s = s;
int n = s.length();
f = new Integer[n][n];
return dfs(0, n - 1);
}
private int dfs(int i, int j) {
if (i >= j) {
return 0;
}
if (f[i][j] != null) {
return f[i][j];
}
int ans = 1 << 30;
if (s.charAt(i) == s.charAt(j)) {
ans = dfs(i + 1, j - 1);
} else {
ans = Math.min(dfs(i + 1, j), dfs(i, j - 1)) + 1;
}
return f[i][j] = ans;
}
}
// Accepted solution for LeetCode #1312: Minimum Insertion Steps to Make a String Palindrome
func minInsertions(s string) int {
n := len(s)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
for j := range f[i] {
f[i][j] = -1
}
}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if i >= j {
return 0
}
if f[i][j] != -1 {
return f[i][j]
}
ans := 1 << 30
if s[i] == s[j] {
ans = dfs(i+1, j-1)
} else {
ans = min(dfs(i+1, j), dfs(i, j-1)) + 1
}
f[i][j] = ans
return ans
}
return dfs(0, n-1)
}
# Accepted solution for LeetCode #1312: Minimum Insertion Steps to Make a String Palindrome
class Solution:
def minInsertions(self, s: str) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= j:
return 0
if s[i] == s[j]:
return dfs(i + 1, j - 1)
return 1 + min(dfs(i + 1, j), dfs(i, j - 1))
return dfs(0, len(s) - 1)
// Accepted solution for LeetCode #1312: Minimum Insertion Steps to Make a String Palindrome
struct Solution;
use std::collections::HashMap;
impl Solution {
fn min_insertions(s: String) -> i32 {
let n = s.len();
let s: Vec<char> = s.chars().collect();
let mut memo: HashMap<(usize, usize), i32> = HashMap::new();
Self::dp(0, n, &mut memo, &s)
}
fn dp(start: usize, end: usize, memo: &mut HashMap<(usize, usize), i32>, s: &[char]) -> i32 {
let n = end - start;
if n < 2 {
return 0;
}
if let Some(&res) = memo.get(&(start, end)) {
return res;
}
let res = if s[start] == s[end - 1] {
Self::dp(start + 1, end - 1, memo, s)
} else {
1 + Self::dp(start, end - 1, memo, s).min(Self::dp(start + 1, end, memo, s))
};
memo.insert((start, end), res);
res
}
}
#[test]
fn test() {
let s = "zzazz".to_string();
let res = 0;
assert_eq!(Solution::min_insertions(s), res);
let s = "mbadm".to_string();
let res = 2;
assert_eq!(Solution::min_insertions(s), res);
let s = "leetcode".to_string();
let res = 5;
assert_eq!(Solution::min_insertions(s), res);
let s = "g".to_string();
let res = 0;
assert_eq!(Solution::min_insertions(s), res);
let s = "no".to_string();
let res = 1;
assert_eq!(Solution::min_insertions(s), res);
}
// Accepted solution for LeetCode #1312: Minimum Insertion Steps to Make a String Palindrome
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1312: Minimum Insertion Steps to Make a String Palindrome
// class Solution {
// private Integer[][] f;
// private String s;
//
// public int minInsertions(String s) {
// this.s = s;
// int n = s.length();
// f = new Integer[n][n];
// return dfs(0, n - 1);
// }
//
// private int dfs(int i, int j) {
// if (i >= j) {
// return 0;
// }
// if (f[i][j] != null) {
// return f[i][j];
// }
// int ans = 1 << 30;
// if (s.charAt(i) == s.charAt(j)) {
// ans = dfs(i + 1, j - 1);
// } else {
// ans = Math.min(dfs(i + 1, j), dfs(i, j - 1)) + 1;
// }
// return f[i][j] = ans;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.