Longest Palindromic Substring

Asked atPaytm
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

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 here

javascript

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+
  1. 01Consider both odd and even centers
  2. 02Expand while indices are valid and characters match
  3. 03Update best start and length after each expansion
  4. 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

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question