VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-size-substring-to-be-removed-to-make-a-given-string-palindromic/

⇱ Minimum size substring to be removed to make a given string palindromic - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum size substring to be removed to make a given string palindromic

Last Updated : 15 Jul, 2025

Given a string S, the task is to print the string after removing the minimum size substring such that S is a palindrome or not.

Examples:

Input: S = "pqrstsuvwrqp"
Output: pqrstsrqp
Explanation:
Removal of the substring "uvw" modifies S to a palindromic string.

Input: S = "geeksforskeeg"
Output: geeksfskeeg
Explanation:
Removal of substring "or" modifies S to a palindromic string.

Approach:

The idea is to include maximum size prefix and suffix from the given string S whose concatenation forms a palindrome. Then, choose the maximum length prefix or suffix from the remaining string which is a palindrome in itself.

Below is the illustration of the approach with the help of an image:

πŸ‘ explanation-copy


Below is the implementation of the above approach:


Output
geeksfskeeg

Time Complexity: O(N2
Auxiliary Space: O(N)

The idea is to choose the longest prefix and suffix such that they form a palindrome. After that from the remaining string we choose the longest prefix or suffix which is a palindrome. For computing the longest palindromic prefix(or suffix) we use Prefix Function which will take linear time to determine it.

Follow the steps to solve the above problem:

  • Find the longest prefix(say s[0, l]) which is also a palindrome of the suffix(say s[n-l, n-1]) of the string str. Prefix and Suffix don’t overlap.
  • Out of the remaining substring(s[l+1, n-l-1]), find the longest palindromic substring(say t) which is either a suffix or prefix of the remaining string.
  • The concatenation of s[0, l]t and s[n-l, n-l-1] is the longest palindromic substring.

Below is the implementation of above approach:


Output
geeksrskeeg

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(N)

Comment