VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-appends-needed-make-string-palindrome/

⇱ Minimum number of Appends needed to make a string palindrome - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of Appends needed to make a string palindrome

Last Updated : 16 Nov, 2024

Given a string s, the task is to find the minimum characters to be appended (insertion at the end) to make a string palindrome. 

Examples:

Input: s = "abede"
Output : 2
Explanation: We can make string palindrome as "abedeba" by adding ba at the end of the string.

Input: s = "aabb"
Output : 2
Explanation: We can make string palindrome as"aabbaa" by adding aa at the end of the string.

Check palindrome every time - O(n^2) Time and O(n) Space

The solution involves progressively removing characters from the beginning of the string, one by one, until the string becomes a palindrome. The answer will be total number of character removed.

For example, consider the string s = "abede". We first check if the entire string is a palindrome, which it isn't. Next, we remove the first character, resulting in the string "bede". We check again, but it's still not a palindrome. We then remove another character from the start, leaving "ede". This time, the string is a palindrome. Therefore, the output is 2, representing the number of characters removed from the beginning to achieve a palindrome.


Output
2

Using Knuth Morris Pratt Algorithm - O(n) Time and O(n) Space

The basic idea behind the approach is that we calculate the largest substring from the end and the length of the string minus this value is the minimum number of appends. The logic is intuitive, we need not append the palindrome and only those which do not form the palindrome. To find this largest palindrome from the end, we reverse the string, calculate the DFA.

The DFA (Deterministic Finite Automaton) mentioned in the context of the Knuth Morris Pratt Algorithm is a concept used to help find the longest prefix of a string that is also a suffix and reverse the string again(thus gaining back the original string) and find the final state, which represents the number of matches of the string with the revered string and hence we get the largest substring that is a palindrome from the end.


Output
2

Related Article : 

Comment
Article Tags:
Article Tags: