You are given a string ‘STR’. Your task is to find the shortest palindrome that can be formed by adding characters in front of ‘STR’.
For example:You are given ‘STR’ = “aabcd”. Then our answer will be “dcbaabcd”. We can form a palindrome by adding ‘d’, ‘c’, and ‘b’ in front of ‘STR’.
The first line contains an integer 'T' which denotes the number of test cases.
The first line of each test case contains a string denoting the input string.
Output Format:
For each test case, print the shortest palindrome that can be formed by adding characters in front of ‘STR’.
The output of each test case will be printed in a separate line.
1 <= T <= 10
1 <= STR.LENGTH <= 5000
‘STR’ contains only lowercase English letters.
Time limit: 1 sec
Note:
You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
2
aabcd
abad
dcbaabcd
dabad
For the first test case, you are given ‘STR’ = “aabcd”. Then our answer will be “dcbaabcd”. We can form a palindrome by adding ‘d’, ‘c’, and ‘b’ in front of ‘STR’.
For the second test case, you are given ‘STR’ = “abad”. Then our answer will be “dabad”. We can form a palindrome by adding ‘d’ in front of ‘STR’.
2
abda
acbbca
adbabda
acbbca
Find the palindromic substring of the input string.
In this approach, we will find the largest palindromic substring of ‘STR’ from the beginning, and we will reverse the remaining substring of ‘STR’ and append it to the beginning of ‘STR’.
5454545
Let’s write ‘STR’ as ‘PSTR’ + ‘RSTR’, where ‘PSTR’ is the palindromic substring of ‘STR’ and ‘RSTR’ is the remaining substring of ‘STR’. Then our answer would be REVERSE(‘RSTR’) + ‘STR’.5454545
Algorithm:
O(N ^ 2), where N is the length of the input string ‘STR’.
We are iterating from 0 to N, and in each iteration, we compare two strings of linear size. Comparing two strings of linear length takes O(N) time. Hence, the overall time complexity will be O(N ^ 2).
O(N), where N is the length of the input string ‘STR’.
The extra space is used to store the reverse of the input string ‘STR’. The size of string ‘REV’ is N. Hence, the overall space complexity is O(N).