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:
C++
// C++ program to find the shortest
// palindromic substring
#include <bits/stdc++.h>
using namespace std;
// Function return the shortest
// palindromic substring
string ShortestPalindrome(string s)
{
int n = s.length();
vector<string> v;
// One by one consider every character
// as center point of even and length
// palindromes
for (int i = 0; i < n; i++)
{
int l = i;
int r = i;
string ans1 = "";
string ans2 = "";
// Find the longest odd length palindrome
// with center point as i
while (l >= 0 && r < n && s[l] == s[r])
{
ans1 += s[l];
l--;
r++;
}
l = i - 1;
r = i;
// Find the even length palindrome
// with center points as i-1 and i.
while (l >= 0 && r < n && s[l] == s[r])
{
ans2 += s[l];
l--;
r++;
}
v.push_back(ans1);
v.push_back(ans2);
}
string ans = v[0];
// Smallest substring which is
// not empty
for (int i = 0; i < v.size(); i++)
{
if (v[i] != "")
{
ans = min(ans, v[i]);
}
}
return ans;
}
// Driver code
int main()
{
string s = "geeksforgeeks";
cout << ShortestPalindrome(s);
return 0;
}
Java
// Java program to find the shortest
// palindromic substring
import java.util.*;
import java.io.*;
class GFG{
// Function return the shortest
// palindromic substring
public static String ShortestPalindrome(String s)
{
int n = s.length();
Vector<String> v = new Vector<String>();
// One by one consider every character
// as center point of even and length
// palindromes
for(int i = 0; i < n; i++)
{
int l = i;
int r = i;
String ans1 = "";
String ans2 = "";
// Find the longest odd length palindrome
// with center point as i
while (l >= 0 && r < n &&
s.charAt(l) == s.charAt(r))
{
ans1 += s.charAt(l);
l--;
r++;
}
l = i - 1;
r = i;
// Find the even length palindrome
// with center points as i-1 and i.
while (l >= 0 && r < n &&
s.charAt(l) == s.charAt(r))
{
ans2 += s.charAt(l);
l--;
r++;
}
v.add(ans1);
v.add(ans2);
}
String ans = v.get(0);
// Smallest substring which is
// not empty
for(int i = 0; i < v.size(); i++)
{
if (v.get(i) != "")
{
if (ans.charAt(0) >=
v.get(i).charAt(0))
{
ans = v.get(i);
}
}
}
return ans;
}
// Driver code
public static void main(String []args)
{
String s = "geeksforgeeks";
System.out.println(ShortestPalindrome(s));
}
}
// This code is contributed by rag2127
Python3
# Python3 program to find the shortest
# palindromic substring
# Function return the shortest
# palindromic substring
def ShortestPalindrome(s) :
n = len(s)
v = []
# One by one consider every character
# as center point of even and length
# palindromes
for i in range(n) :
l = i
r = i
ans1 = ""
ans2 = ""
# Find the longest odd length palindrome
# with center point as i
while ((l >= 0) and (r < n) and (s[l] == s[r])) :
ans1 += s[l]
l -= 1
r += 1
l = i - 1
r = i
# Find the even length palindrome
# with center points as i-1 and i.
while ((l >= 0) and (r < n) and (s[l] == s[r])) :
ans2 += s[l]
l -= 1
r += 1
v.append(ans1)
v.append(ans2)
ans = v[0]
# Smallest substring which is
# not empty
for i in range(len(v)) :
if (v[i] != "") :
ans = min(ans, v[i])
return ans
s = "geeksforgeeks"
print(ShortestPalindrome(s))
# This code is contributed by divyesh072019
C#
// C# program to find the shortest
// palindromic substring
using System;
using System.Collections.Generic;
class GFG
{
// Function return the shortest
// palindromic substring
static string ShortestPalindrome(string s)
{
int n = s.Length;
List<string> v = new List<string>();
// One by one consider every character
// as center point of even and length
// palindromes
for(int i = 0; i < n; i++)
{
int l = i;
int r = i;
string ans1 = "";
string ans2 = "";
// Find the longest odd length palindrome
// with center point as i
while(l >= 0 && r < n && s[l] == s[r])
{
ans1 += s[l];
l--;
r++;
}
l = i - 1;
r = i;
// Find the even length palindrome
// with center points as i-1 and i.
while(l >= 0 && r < n && s[l] == s[r])
{
ans2 += s[l];
l--;
r++;
}
v.Add(ans1);
v.Add(ans2);
}
string ans = v[0];
// Smallest substring which is
// not empty
for(int i = 0; i < v.Count; i++)
{
if(v[i] != "")
{
if(ans[0] >= v[i][0])
{
ans = v[i];
}
}
}
return ans;
}
// Driver code
static public void Main ()
{
string s = "geeksforgeeks";
Console.WriteLine(ShortestPalindrome(s));
}
}
// This code is contributed by avanitrachhadiya2155
JavaScript
<script>
// Javascript program to find the shortest
// palindromic substring
// Function return the shortest
// palindromic substring
function ShortestPalindrome(s)
{
let n = s.length;
let v = [];
// One by one consider every character
// as center point of even and length
// palindromes
for(let i = 0; i < n; i++)
{
let l = i;
let r = i;
let ans1 = "";
let ans2 = "";
// Find the longest odd length palindrome
// with center point as i
while(l >= 0 && r < n && s[l] == s[r])
{
ans1 += s[l];
l--;
r++;
}
l = i - 1;
r = i;
// Find the even length palindrome
// with center points as i-1 and i.
while(l >= 0 && r < n && s[l] == s[r])
{
ans2 += s[l];
l--;
r++;
}
v.push(ans1);
v.push(ans2);
}
let ans = v[0];
// Smallest substring which is
// not empty
for(let i = 0; i < v.length; i++)
{
if(v[i] != "")
{
if(ans[0] >= v[i][0])
{
ans = v[i];
}
}
}
return ans;
}
let s = "geeksforgeeks";
document.write(ShortestPalindrome(s));
// This code is contributed by decode2207.
</script>
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:
C++
// C++ program to find the shortest
// palindromic substring
#include <bits/stdc++.h>
using namespace std;
// Function return the shortest
// palindromic substring
char ShortestPalindrome(string s)
{
int n = s.length();
char ans = s[0];
// Finding the smallest character
// present in the string
for(int i = 1; i < n ; i++)
{
ans = min(ans, s[i]);
}
return ans;
}
// Driver code
int main()
{
string s = "geeksforgeeks";
cout << ShortestPalindrome(s);
return 0;
}
Java
// Java program to find the shortest
// palindromic subString
class GFG{
// Function return the shortest
// palindromic subString
static char ShortestPalindrome(String s)
{
int n = s.length();
char ans = s.charAt(0);
// Finding the smallest character
// present in the String
for(int i = 1; i < n; i++)
{
ans = (char) Math.min(ans, s.charAt(i));
}
return ans;
}
// Driver code
public static void main(String[] args)
{
String s = "geeksforgeeks";
System.out.print(ShortestPalindrome(s));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program to find the shortest
# palindromic substring
# Function return the shortest
# palindromic substring
def ShortestPalindrome(s):
n = len(s)
ans = s[0]
# Finding the smallest character
# present in the string
for i in range(1, n):
ans = min(ans, s[i])
return ans
# Driver code
s = "geeksforgeeks"
print(ShortestPalindrome(s))
# This code is contributed by divyeshrabadiya07
C#
// C# program to find the shortest
// palindromic subString
using System;
class GFG{
// Function return the shortest
// palindromic subString
static char ShortestPalindrome(String s)
{
int n = s.Length;
char ans = s[0];
// Finding the smallest character
// present in the String
for(int i = 1; i < n; i++)
{
ans = (char) Math.Min(ans, s[i]);
}
return ans;
}
// Driver code
public static void Main(String[] args)
{
String s = "geeksforgeeks";
Console.Write(ShortestPalindrome(s));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to find the shortest
// palindromic subString
// Function return the shortest
// palindromic subString
function ShortestPalindrome(s)
{
let n = s.length;
let ans = s[0].charCodeAt();
// Finding the smallest character
// present in the String
for(let i = 1; i < n; i++)
{
ans = Math.min(ans, s[i].charCodeAt());
}
return String.fromCharCode(ans);
}
// Driver code
let s = "geeksforgeeks";
document.write(ShortestPalindrome(s));
// This code is contributed by suresh07
</script>
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.
Similar Reads
Shortest Superstring Problem Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: Input: arr[] = {"geeks", "quiz", "for"}Output: geeksquizforExplanation: "geeksquizfor" contains all the thr
15+ min read
Longest Palindromic Substring Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring.Examples:Input: s = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "ee
12 min read
Palindrome Substrings Count Given a string s, the task is to count all palindromic substrings of length more than one.Examples:Input: s = "abaab"Output: 3Explanation: Palindromic substrings with length greater than 1, are "aba", "aa", and "baab".Input: s = "aaa"Output: 3Explanation: Palindromic substrings with length greater t
15+ min read
Longest Non-palindromic substring Given a string of size n. The task is to find the length of the largest substring which is not a palindrome. Examples: Input : abba Output : 3 Here maximum length non-palindromic substring is 'abb' which is of length '3'. There could be other non-palindromic sub-strings also of length three like 'bb
7 min read
Substring Sort Given n strings, we need to sort those strings such that every string is a substring of all strings after it. If not possible to sort, then print the same. Examples: Input : {"d", "zddsaaz", "ds", "ddsaa", "dds"} Output : d ds dds ddsaa zddsaaz Input : {"geeks", "ee", "geeksforgeeks", "forgeeks", "e
12 min read
Palindrome String Coding Problems A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
Rearrange string to obtain Longest Palindromic Substring Given string str, the task is to rearrange the given string to obtain the longest palindromic substring. Examples: Input: str = âgeeksforgeeksâOutput: eegksfskgeeorExplanation: eegksfskgee is the longest palindromic substring after rearranging the string.Therefore, the required output is eegksfskgee
9 min read
Palindrome Partitioning Given a string s, the task is to find the minimum number of cuts needed for palindrome partitioning of the given string. A partitioning of the string is a palindrome partitioning if every sub-string of the partition is a palindrome.Examples: Input: s = "geek" Output: 2 Explanation: We need to make m
15+ min read
Print Longest Palindromic Subsequence Given a sequence, print a longest palindromic subsequence of it. Examples : Input : BBABCBCAB Output : BABCBAB The above output is the longest palindromic subsequence of given sequence. "BBBBB" and "BBCBB" are also palindromic subsequences of the given sequence, but not the longest ones. Input : GEE
11 min read
Length of Longest Palindrome Substring Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string. Examples: Input: S = "abcbab"Output: 5Explanation: string "abcba" is the longest substring that is a palindrome which is of length 5. Input: S = "abcdaa"Output: 2Explanation: string
15+ min read