Longest Palindromic Substring

You are given a string ('STR') of length 'N'. Find the longest palindromic substring. If there is more than one palindromic substring with the maximum length, return the one with the smaller start index.

Note:
A substring is a contiguous segment of a string.

For example : The longest palindromic substring of "ababc" is "aba", since "aba" is a palindrome and it is the longest substring of length 3 which is a palindrome, there is another palindromic substring of length 3 is "bab" since "aba" starting index is less than "bab", so "aba" is the answer.

Input Format:
The first line of input contains a single integer 'T', representing the number of test cases or queries to be run.
Then the 'T' test cases follow.

The first and only one of each test case contains a string 'STR'.
Output Format :
For every test case, print the longest palindromic substring. 

If there are multiple possible answers then you need to print the substring which has the lowest starting index.
Note :
Do not print anything. It has already been taken care of. Just implement the given function.
Follow up:
Try to solve it using O(1) space complexity.
Constraints :
1 <= T <= 5
0 <= N <= 100

Time Limit: 1 sec
CodingNinjas
author
2y
Brute Force
  1. Generate substrings of the given string such that substring having greater length will be generated first.
  2. To do this, run a loop where iterator len will go from N to 1, where N is the lengt...read more
CodingNinjas
author
2y
Dynamic Programming
  1. If the string length is less than or equal to 1 then return the string, as one length string is always palindromic.
  2. Initialize a DP array of data type boolean, DP[i][j] will store fa...read more
CodingNinjas
author
2y
Expanding around the centres
  1. If the string length is less than or equal to 1 then return the string, as a single character is always palindromic.
  2. The idea is to generate all even length and odd length p...read more
CodingNinjas
author
2y
Manacher’s Algorithm

Manacher’s algorithm optimizes our solution by using some insights into how palindromes work.

Let C be the center of the longest length palindrome we have encountered till now. And ...read more

Add answer anonymously...
Optum 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