DEV Community

Cover image for Longest palindromic substring in s
chandra penugonda
chandra penugonda

Posted on • Edited on

Longest palindromic substring in s

This problem was asked by Uber.

You are given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example

function longestPalindrome(s) {

}

console.log(longestPalindrome('babad')); // bab
console.log(longestPalindrome('cbbd')); // bb
Enter fullscreen mode Exit fullscreen mode

Solution

function longestPalindrome(s) {
  let longest = "";
  for (let i = 0; i < s.length; i++) {
    const oddStr = expandFromMiddle(s, i, i);
    if (oddStr.length > longest.length) {
      longest = oddStr;
    }

    const evenStr = expandFromMiddle(s, i, i + 1);
    if (evenStr.length > longest.length) {
      longest = evenStr;
    }
  }

  function expandFromMiddle(str, left, right) {
    while (left >= 0 && right < str.length && s[left] === s[right]) {
      left--;
      right++;
    }
    return str.slice(left + 1, right);
  }
  return longest;
}
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Iterate through each character in the string
  • For each character, expand outwards to find odd and even length palindromes centered at that character
  • Use a helper function to expand from the middle, incrementing left and right pointers until reaching different characters
  • Keep track of the longest palindrome seen so far
  • After checking all characters, return the longest palindrome

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay