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: Make "zzazz" PalindromicInput:"zzazz"Not palindromicProcess:Compare from both endsFind minimum insertions neededDP Table SolutionOutput:2Minimum stepsPossible Result After 2 Insertions:zzzazzzinsertinsert"zzzazzz" is palindromic!
Understanding the Visualization
1
Input String
Given string that needs to become palindromic
2
Find Strategy
Determine minimum characters needed to insert
3
Result
Return the minimum number of insertion steps
Key Takeaway
🎯 Key Insight: Minimum insertions = string length - longest palindromic subsequence length
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
89.5K 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