101 Logo
onenoughtone

Problem Statement

Palindrome Maker

You are a text editor working on a new feature that helps users create palindromes from their input text. A palindrome is a string that reads the same forward and backward. For example, "racecar" and "level" are palindromes.

Given a string s, your task is to find the minimum number of characters you need to insert into the string to make it a palindrome. You can insert characters anywhere in the string.

For example, if the input string is "ab", you can insert "a" at the end to get "aba", which is a palindrome. So the minimum number of insertions needed is 1.

Examples

Example 1:

Input: s = "zzazz"
Output: 0
Explanation: The string is already a palindrome, so no insertions are needed.

Example 2:

Input: s = "mbadm"
Output: 2
Explanation: Insert 'b' and 'a' to get 'mbadabm'. Note that there are multiple ways to get a palindrome (e.g., 'mdbabdm'), but the minimum number of insertions is always 2.

Example 3:

Input: s = "leetcode"
Output: 5
Explanation: Insert 'e', 'd', 'o', 'c', and 'e' to get 'leetcodocteel'.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Problem Breakdown

To solve this problem, we need to:

  1. The key insight is that the minimum number of insertions needed is related to the longest palindromic subsequence (LPS) of the string.
  2. If we find the LPS of length k in a string of length n, then we need to insert n - k characters to make the entire string a palindrome.
  3. We can use dynamic programming to find the LPS of the string.
  4. Alternatively, we can directly compute the minimum insertions needed using dynamic programming.
ProblemSolutionCode
101 Logo
onenoughtone