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.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we do not need any insertions.
Example 2:
Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".
Example 3:
Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".
Constraints:
1 <= s.length <= 500
s consists of lowercase English letters.
Solutions
Solution 1
Thinking
We want the fewest insertions that make \(s\) a palindrome. Enumerating insertion plans is hopeless for \(n \le 500\). A subproblem is an interval: matching ends reduce to the open interval; otherwise we insert a copy of one end beside the other and take the cheaper side plus one.
Intervals overlap, so the same \((i,j)\) is asked many times. Memoizing \(dfs(i,j)\) evaluates each interval once, in \(O(n^2)\).
Memoization still uses a call stack and a cache. The same recurrence as a table \(f[i][j]\), filled with \(i\) decreasing and \(j\) increasing, makes \(f[i+1][j-1]\), \(f[i+1][j]\), and \(f[i][j-1]\) already known, so the recursion disappears.
Filling by endpoint indices is only one valid order. Enumerating interval length \(k\) and then the left end \(i\) (with \(j=i+k-1\)) computes shorter intervals first. The transition is unchanged; only an outer length loop is added.