Skip to problem
←

Minimum Insertion Steps to Make a String Palindrome

Hard 0 attempts

Given a string s, work out the fewest characters you'd need to insert — at any positions — so that the resulting string reads the same forwards and backwards.

Each step inserts one character anywhere, including at either end. You cannot delete, replace, or reorder existing characters. Return the count, not the resulting palindrome.

For "ab", insert "a" at the end to form "aba", so return 1. An existing palindrome needs 0 insertions.

Function contract

Implement minInsertions(s). Receive a nonempty string of lowercase English letters.

Output: Return the minimum number of single-character insertions needed to form a palindrome.

Example 1

Input
s = "leetcode"
Output
5

Example 2

Input
s = "zzazz"
Output
0
Constraints
  • 1 <= s.length <= 500
  • s consists of lowercase English letters

LCS with Reverse

Keep a longest palindromic subsequence of length L unchanged and supply matching characters for the other n - L characters. The minimum insertion count is n - L. The length L equals the longest common subsequence length of s and its reverse; contiguity is not required.

Compute that length row by row. A match extends the previous row’s diagonal; a mismatch chooses the best result from skipping one character in either string. Copying the prior row before updating keeps those dependencies intact.

javascript
function minInsertions(s) {
  const n = s.length, t = s.split('').reverse().join('');
  const dp = Array(n+1).fill(0);
  for (let i = 1; i <= n; i++) {
    const prev = [...dp];
    for (let j = 1; j <= n; j++)
      dp[j] = s[i-1]===t[j-1] ? prev[j-1]+1 : Math.max(dp[j-1], prev[j]);
  }
  return n - dp[n];
}

Time: O(n²) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript