Minimum Insertion Steps to Make a String Palindrome solution explained
Minimum Insertion Steps to Make a String Palindrome asks how many characters you must insert, anywhere, to turn a string into a palindrome. Work on the substring s[i..j]: if its two ends match, they can face each other in the final palindrome and the answer is the inside's answer; if not, one end needs a new partner, so add 1 to the better of dropping the left end or the right end. The answer is also n minus the longest palindromic subsequence. Either way it is O(n²) time, and the table shrinks to one row of length n.
By Evin JohnPublished 8 min read
The problem, restated
You get a string. In one step you may insert any single character at any position. Return the smallest number of steps after which the string is a palindrome. Characters already in the string are never removed or changed.
| String | Insertions | Result built by the code below |
|---|---|---|
| abca | 1 | abcba |
| race | 3 | racecar |
| 2 | elgoogle | |
| aabb | 2 | aabbaa |
| level | 0 | level |
For "aabb" the longest palindromic subsequence is "aa" or "bb", length 2, so 4 - 2 = 2 insertions are needed; keeping the b's and mirroring the two a's gives aabbaa.
What the interviewer is checking
Two routes lead to the answer, and interviewers like hearing both. One is the direct interval DP: decide what happens to the two ends of a substring. The other is the reduction: the characters you do not insert must already form a palindrome, so you keep the longest palindromic subsequence and insert a partner for everything else. Spotting that the reduction ties this problem to LCS is the kind of connection that reads as experience.
Questions to ask
- Can I insert at the ends as well as in the middle? Yes, anywhere.
- Do you need the palindrome or just the count? Usually the count; offer to build the string.
- Is the input already lowercase letters? It does not change the algorithm.
Brute force
One exhaustive route searches over insertions directly: from the string, try inserting each candidate letter at each position, level by level, until some result is a palindrome. That is a breadth-first search whose frontier multiplies by roughly n times the alphabet size at every level. A tamer exhaustive route uses the fact proved next: list all 2^n subsequences, keep the longest palindrome among them, and subtract its length from n. This page's tests used both on short strings to confirm the DP.
Why the count is n minus the longest palindromic subsequence
After insertions, the original characters still appear in order inside the final palindrome. Pair each original character with the character in its mirror position. Characters paired with each other, plus possibly one in the middle, form a palindromic subsequence of the original string. Every other original character is paired with an inserted one, so the number of insertions is at least n minus the longest palindromic subsequence. Inserting a mirror partner for each character outside that subsequence achieves it, so the bound is exact.
The interval DP
For substring s[i..j]: if s[i] equals s[j], they can be mirror partners, and the cost is the cost of the inside. If they differ, at least one of them gets an inserted partner. Giving s[i] a partner at the far right costs 1 plus the cost of s[i + 1..j]; giving s[j] a partner at the far left costs 1 plus the cost of s[i..j - 1]. Take the cheaper. Substrings of length 0 or 1 cost nothing.
def min_insertions(s):
n = len(s)
ins = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
ins[i][j] = ins[i + 1][j - 1]
else:
ins[i][j] = 1 + min(ins[i + 1][j], ins[i][j - 1])
return ins[0][n - 1] if n else 0When j = i + 1 and the two letters match, ins[i + 1][j - 1] reads ins[i + 1][i], a cell below the diagonal that is never written and stays 0. That is the right value for an empty inside.
One row of memory
Row i only reads row i + 1 and its own earlier cells. Keep one array for row i + 1 and update it in place left to right, saving the old value of the cell to the left before overwriting it; that saved value is the diagonal ins[i + 1][j - 1] for the next column.
def min_insertions_row(s):
n = len(s)
row = [0] * n
for i in range(n - 2, -1, -1):
diag = 0
for j in range(i + 1, n):
below = row[j]
if s[i] == s[j]:
row[j] = diag
else:
row[j] = 1 + min(below, row[j - 1])
diag = below
return row[n - 1] if n else 0function minInsertions(s) {
const n = s.length;
const row = new Array(n).fill(0);
for (let i = n - 2; i >= 0; i--) {
let diag = 0;
for (let j = i + 1; j < n; j++) {
const below = row[j];
row[j] = s[i] === s[j] ? diag : 1 + Math.min(below, row[j - 1]);
diag = below;
}
}
return n ? row[n - 1] : 0;
}At the start of each row, diag is 0 because the first cell, j = i + 1, has an empty inside. When j = i + 1, the code reads row[i], which no earlier row has written yet, so it is still 0, the right cost for the one-letter substring s[i..i].
Building one shortest palindrome
With the full table, walk inward from (0, n - 1). Matching ends go to both sides of the result. Otherwise follow the cheaper option: if dropping the left end is cheaper, put s[i] on both sides (the right copy is the insertion) and move i forward; else put s[j] on both sides and move j back.
def build_palindrome(s):
n = len(s)
if n == 0:
return ""
ins = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
ins[i][j] = ins[i + 1][j - 1]
else:
ins[i][j] = 1 + min(ins[i + 1][j], ins[i][j - 1])
front, back = [], []
i, j = 0, n - 1
while i <= j:
if i == j:
front.append(s[i])
break
if s[i] == s[j]:
front.append(s[i])
back.append(s[j])
i += 1
j -= 1
elif ins[i + 1][j] <= ins[i][j - 1]:
front.append(s[i])
back.append(s[i])
i += 1
else:
front.append(s[j])
back.append(s[j])
j -= 1
return "".join(front) + "".join(reversed(back))Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Recursion without a cache | Exponential | O(n) stack |
| Interval table | O(n²) | O(n²) |
| One row | O(n²) | O(n) |
| n minus LCS with the reversed string | O(n²) | O(n) with one row |
Edge cases
- Empty string or one character: 0.
- Already a palindrome: 0, and the table only ever takes the matching branch on the outer pairs.
- All distinct characters: n - 1, since the longest palindromic subsequence is a single letter.
- Two letters that differ: 1.
Common mistakes
- Counting mismatched mirror pairs of the original string, which ignores that insertions shift positions. "aabb" has two mismatched pairs, which happens to match, but "abcd" has two and needs 3.
- Confusing subsequence with substring: the kept characters need not be adjacent.
- Filling the table with i going up, which reads ins[i + 1][...] before it exists.
- In the one-row version, forgetting to reset diag to 0 at the start of each row.
- Mixing up this problem with the shortest palindrome made by adding characters only at the front, which is a different question with a different answer.
How to explain it out loud
Fictional example
- Candidate
- Look at the two ends of the substring. If they match, they can be mirror images in the final palindrome, so the cost is whatever the inside costs. If not, one of them needs an inserted partner, so it is one plus the better of the two shorter substrings.
- Candidate
- Another way to see it: characters I never pair with an insertion must already form a palindrome, so I keep the longest palindromic subsequence and insert for the rest. That is n minus LPS, and LPS is the LCS of the string with its reverse.
- Interviewer
- Memory?
- Candidate
- Each row only needs the row below, so one array of length n with a saved diagonal is enough.
Related problems
Shortest Common Supersequence is the two-string cousin: insert characters so that one string contains two others, again built from LCS. Uncrossed Lines is LCS in disguise on integer arrays. Palindrome Partitioning II cuts a string into palindromes instead of extending it, and Longest Common Subsequence covers the table this page reduces to.
Practicing with Natively
The n - LPS argument is short, but only if you have said it before. Rehearse it in a mock session on Mac or Windows with Natively transcribing, then read back whether the explanation made sense without the code. Once you have your own solution, Natively can read the problem from a screenshot and suggest an approach to compare. See the AI interview assistant.
Questions people ask
How do you solve Minimum Insertion Steps to Make a String Palindrome?
Use ins(i, j) = ins(i + 1, j - 1) when s[i] == s[j], otherwise 1 + min(ins(i + 1, j), ins(i, j - 1)), with 0 for substrings of length 0 or 1. The answer is ins(0, n - 1).
Why is the answer n minus the longest palindromic subsequence?
Characters that are not paired with an inserted character must already form a palindrome, so you keep the longest one and insert a mirror partner for each other character.
What is the time complexity?
O(n squared) time. The full table uses O(n squared) memory, and a single row with a saved diagonal uses O(n).
Can I get the palindrome itself?
Yes. Walk the full table from the outside in: matching ends go on both sides; otherwise copy the end whose removal is cheaper to both sides.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
