Longest Palindromic Substring
The problem
Given a string s, return the **longest palindromic **substring in s.
A palindromic substring is a contiguous sequence of characters within the string that reads the same forward and backward.
**Input: **s = "babad" Output: "bab" Explanation: Both "bab" and "aba" are valid palindromic substrings of length 3. Return either.
Input: s = "cbbd" **Output: **"bb" Explanation: The longest palindrome is "bb" of length 2.
**Input: **s = "a12321b"
- 1 <= s.length <= 1000
- s consists of only English letters (both lowercase and uppercase) and digits.
cpp
class Solution {
public:
string longestPalindrome(string s) {
// Your code goes here
}
};java
class Solution {
public String longestPalindrome(String s) {
// Your code goes here
}
}python
class Solution:
def longestPalindrome(self, s: str) -> str:
# Your code goes herejavascript
class Solution {
longestPalindrome(s) {
// Your code goes here
}
}csharp
public class Solution
{
public string LongestPalindrome(string s)
{
// Your code goes here
}
}go
func longestPalindrome(s string) string {Stuck? Show a way to structure it+
- 01Consider both odd and even centers
- 02Expand while indices are valid and characters match
- 03Update best start and length after each expansion
- 04Return the best slice
Reference answer
Then expect these follow-ups
When would you use Manacher's algorithm?
Tests: follow-up reasoning
How does DP compare in space?
Tests: complexity analysis
Hiring now
Paytm has 128 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Senior Software Engineer – Backend (Travel)
Bangalore, Karnataka
Junior Marketing Manager
Luxembourg
Collection Manager- North- Business- Lending Collections
Aligarh, Uttar Pradesh
Next question