Minimum Insertions to Make String Palindrome
Implement minInsertions
Given a string `s`, find the minimum number of characters that must be inserted (anywhere in the string) so the result reads the same forwards and backwards.
The trick is to stop thinking about insertions directly and instead ask which characters of `s` are already "safe" — already part of some palindrome hiding inside the string. Any subsequence of `s` that's already a palindrome doesn't need help; everything else eventually needs a mirrored partner planted somewhere to balance it out. So the fewest possible insertions is exactly the length of `s` minus the length of its longest palindromic subsequence: keep that subsequence as the palindrome's "skeleton," and every character left over is one insertion. Finding that longest palindromic subsequence is itself a classic two-pointer interval problem — shrink the string from both ends, matching or dropping a side at each step, and cache the result per interval so it's computed once.
Example 1:
Input: s = "zzazz"
Output: 0
Example 2:
Input: s = "mbadm"
Output: 2
Example 3:
Input: s = "g"
Output: 0
+ 7 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ s.length ≤ 12 - ●
s consists of lowercase English letters
s =
zzazz