HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I find the longest palindromic substring in a JavaScript string?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
longestsubstringjavascripthowfindthecanpalindromicstring

Problem

A palindrome is a string that reads the same backward as forward. For example, 'racecar', 'abba' and 'level' are palindromes. The longest palindromic substring is the longest contiguous substring of a given string that is also a palindrome.
> [!IMPORTANT]
>
> This article is meant as a way to explore ways of thinking and algorithmic techniques, so readers can apply them to various problems. If you're looking for the best solution to this problem, I suggest you check out Manacher's algorithm, which is not explored here.
Checking for a palindrome is straightforward. We can simply reverse the string and check if it is equal to the original string. Here's a simple implementation:

Solution

const isPalindrome = str => {
  const reversed = str.split('').reverse().join('');
  return str === reversed;
};

isPalindrome('racecar');  // true
isPalindrome('abba');     // true
isPalindrome('hello');    // false


>
> This article is meant as a way to explore ways of thinking and algorithmic techniques, so readers can apply them to various problems. If you're looking for the best solution to this problem, I suggest you check out Manacher's algorithm, which is not explored here.
Checking for a palindrome is straightforward. We can simply reverse the string and check if it is equal to the original string. Here's a simple implementation:
Given the previous check, a brute-force solution would be to check every possible substring of the input string and see if it is a palindrome. While inefficient, this approach showcases a two-pointer technique that may be useful in similar problems.
We start at the beginning the string, keeping two pointers: the left pointer points at the start of the substring and the right pointer at the end. We then check if the substring is a palindrome. If it is, we compare the length of the current substring with the longest palindrome found so far. If it is longer, we update our longest palindrome.
When the right pointer reaches the end of the string, we move the left pointer one position to the right and repeat the process until we reach the end of the string.

Code Snippets

const isPalindrome = str => {
  const reversed = str.split('').reverse().join('');
  return str === reversed;
};

isPalindrome('racecar');  // true
isPalindrome('abba');     // true
isPalindrome('hello');    // false
const longestPalindrome = str => {
  let best = { length: 0, value: '' };

  for (let l = 0; l < str.length; l++)
    for (let r = l + best.length; r < str.length; r++) {
      const current = { length: r - l, value: str.slice(l, r + 1) };
      if (!isPalindrome(current.value)) continue;
      if (current.length < best.length) continue;
      best = current;
    }

  return best.value;
};

longestPalindrome('babad'); // 'bab' or 'aba'
longestPalindrome('cbbd'); // 'bb'
const expandAroundCenter = (str, left, right) => {
  while (left >= 0 && right < str.length && str[left] === str[right])
    left--, right++;
  return { left: left + 1, right: right - 1, length: right - left - 1 };
};

const isPalindrome = str => {
  const isEvenLength = str.length % 2 === 0;
  const centerPoints = isEvenLength ?
    [str.length / 2 - 1, str.length / 2] :
    [Math.floor(str.length / 2), Math.floor(str.length / 2)];
  const maxPalindrome = expandAroundCenter(str, ...centerPoints);
  return maxPalindrome.length === str.length
};

isPalindrome('racecar');  // true
isPalindrome('abba');     // true
isPalindrome('hello');    // false

Context

From 30-seconds-of-code: longest-palindrome

Revisions (0)

No revisions yet.