Longest Palindromic Substring

Given a string ’S’ consisting of lower case English letters, you are supposed to return the longest palindromic substring of ‘S’.

Note that in case of more than one longest palindromic substrings with the same length you need to return the rightmost substring in the given string. For example in string “bbbab”, there are two possible longest palindromic substrings i.e. “bbb” and “bab”, and since you are supposed to return the rightmost substring, so you need to return “bab” as the answer.

Note:
A substring is a contiguous sequence of elements within a string (for example, “bcd” is a substring of “abcde” while “bce” is not).

A string is said to be palindrome if the reverse of the string is the same as the actual string. For example, “abba” is a palindrome, but “abbc” is not a palindrome.
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.

The only line of each test case contains a single string ‘S’ consisting of only lowercase English letters.
Output Format:
For each test case, print a single string in a single line denoting the longest palindromic substring of string ‘S’.

The output for each test case is in a separate line.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
1 <= N <= 100

Where ‘N’ is the length of the string.

Time limit: 1 sec
CodingNinjas
author
2y

Approach :

1) Create a 2-D dp boolean vector(with all false initially) where dp[i][j] states whether s[i...j] is a palindrome or not and initilialise a variable ans=1 which will store the final answer....read more

CodingNinjas
author
2y
Brute Force

The brute force solution is to pick all possible starting and ending positions for a substring and verify if it is a palindrome.

The steps are as follows:

  1. If the length of the given string ...read more
CodingNinjas
author
2y
Dynamic Programming

To improve our brute force solution, we first observe how we can avoid unnecessary re-computation while we are validating if a substring is a palindrome or not. Consider the case "x...read more

CodingNinjas
author
2y
Expand Around The Centre

When you observe closely you will realise that a palindrome has mirrors around its centre, a palindrome can be expanded in both directions from its centre.

The steps are as fol...read more

Add answer anonymously...
Nagarro Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter