VOOZH about

URL: https://www.geeksforgeeks.org/dsa/shortest-palindromic-substring/

⇱ Shortest Palindromic Substring - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shortest Palindromic Substring

Last Updated : 29 Dec, 2022

Given a string you need to find the shortest palindromic substring of the string. If there are multiple answers output the lexicographically smallest.

Examples: 

Input: zyzz
Output:y

Input: abab
Output: a

Naive Approach: 

  • The approach is similar to finding the longest palindromic substring. We keep track of even and odd lengths substring and keep storing it in a vector.
  • After that, we will sort the vector and print the lexicographically smallest substring. This may also include empty substrings but we need to ignore them.

Below is the implementation of the above approach:


Output: 
e

 

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

Efficient Approach: An observation here is that a single character is also a palindrome. So, we just need to print the lexicographically smallest character present in the string.

Below is the implementation of the above approach: 


Output: 
e

 

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Comment