Minimum Insertion Steps to Make a String Palindrome - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "zzazz"
Output: 2
💡 Note: Insert 'z' at index 2 and 'a' at index 6 to get "zzzazzz" which is palindromic. We can also insert 'a' at index 1 and 'a' at index 3 to get "zaaazz", but that's not optimal.
Example 2 — Already Palindrome
$ Input: s = "racecar"
Output: 0
💡 Note: The string is already a palindrome, so no insertions are needed.
Example 3 — Single Character
$ Input: s = "a"
Output: 0
💡 Note: Single character is always a palindrome.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of lowercase English letters only

Visualization

Tap to expand
Minimum Insertion Steps to Make a String Palindrome INPUT String s: z z a z z 0 1 2 3 4 Length n = 5 Goal: Insert minimum chars to make string palindrome LPS in "zzazz": "zzazz" (length 5) Already a palindrome! But let's see the approach... ALGORITHM STEPS 1 Find LPS Length Longest Palindromic Subsequence of s 2 Use DP Table dp[i][j] = LPS length for s[i..j] 3 LPS Recurrence if s[i]==s[j]: dp[i][j] = dp[i+1][j-1] + 2 4 Calculate Result Insertions = n - LPS = 5 - 5 = 0 DP Table (diagonal = LPS): dp[0][4] = 5 (full string) "zzazz" is palindrome LPS = 5 FINAL RESULT Original String: z z a z z Palindrome (no change needed): z z a z z Output: 0 Insertions needed Formula: n - LPS = 5 - 5 = 0 Key Insight: The minimum insertions = Length of string - Length of Longest Palindromic Subsequence (LPS). Characters NOT in the LPS need to be "mirrored" by inserting their counterparts. For "zzazz", the entire string is already a palindrome, so LPS = 5 and no insertions are needed. TutorialsPoint - Minimum Insertion Steps to Make a String Palindrome | Longest Palindromic Subsequence Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
89.6K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen