algorithms

5 · two pointers · medium

Longest palindromic substring

Given a string, return its longest substring that reads the same forwards and backwards. Ties can go either way.

Test yourself · 6 cards problem on LeetCode ↗

The one rule

Every palindrome has a center. Odd-length ones center on a character ("bab" on the a), even-length ones sit between two characters ("bb" between the b's). A string of length n has 2n − 1 centers, so instead of asking "is this substring a palindrome?" about every substring, ask "how far does the palindrome around this center reach?" about every center.

if s[l..r] is a palindrome, then
s[l-1..r+1] is a palindrome  ⇔  s[l-1] === s[r+1]

That one line is the whole speedup. Growing a known palindrome by one character on each side costs one comparison, not a rescan. Start at a center, walk l left and r right while the ends match, and stop at the first mismatch or the edge of the string — everything you passed was a palindrome, and the last one is the longest around that center.

Expand around center · O(n²) time, O(1) space

For every index i, try both starts: l = r = i for odd-length palindromes and l = i, r = i + 1 for even-length ones. Expand while in bounds and s[l] === s[r], keep the longest span seen. Both l and r sit inside the palindrome, so its length is r − l + 1 and the slice ends at r + 1.

Step through it. Gold is the pair being compared, blue is the palindrome confirmed so far around the current center, and the bar under the cells is the best answer found. The second input has an even-length answer; the third has a long one, so you can see how quickly most centers die.

comparing palindrome around this center mismatch best so far
var longestPalindrome = function (s) {
  let longestStr = "";
  let longestStrLen = 0;

  for (let i = 0; i < s.length; i++) {
    let l = i, r = i;

    while (l >= 0 && r < s.length && s[l] === s[r]) {
      let diff = r - l + 1;

      if (longestStrLen < diff) {
        longestStr = s.slice(l, r + 1);
        longestStrLen = diff;
      }

      l -= 1;
      r += 1;
    }

    l = i;
    r = i + 1;

    while (l >= 0 && r < s.length && s[l] === s[r]) {
      let diff = r - l + 1;

      if (longestStrLen < diff) {
        longestStr = s.slice(l, r + 1);
        longestStrLen = diff;
      }

      l -= 1;
      r += 1;
    }
  }
  return longestStr;
};

The bug my first version had lived in exactly two characters: r − l and slice(l, r). They were consistent with each other, so nothing crashed — the code just never recorded a single-character palindrome and returned "ba" for "babad". The tell was the smallest input: "a" came back as "". Both ends are inside the span, so it's r − l + 1 and slice(l, r + 1).

Two cleanups for next time: an expand(l, r) helper that runs the loop and returns the span removes the duplicated block, and tracking bestL / bestLen as integers with a single slice at the end makes the space argument airtight — slicing inside the loop copies every candidate.

Brute force, for contrast · O(n³)

var longestPalindrome = function (s) {
  const isPal = (l, r) => {
    while (l < r) {
      if (s[l] !== s[r]) return false;
      l++; r--;
    }
    return true;
  };

  let best = "";
  for (let i = 0; i < s.length; i++) {
    for (let j = i; j < s.length; j++) {
      if (j - i + 1 > best.length && isPal(i, j)) best = s.slice(i, j + 1);
    }
  }
  return best;
};

O(n²) substrings, each checked with an O(n) inward two-pointer scan. Every candidate is checked from scratch even though "bab" and "a" share all their work. Note the same inclusive-span arithmetic here — j − i + 1, slice(i, j + 1) — it's not a one-off, it's what "both ends are inside" always costs.

Why this is filed under DP

The rule at the top is a recurrence. Written as a table it's dp[i][j] = s[i] === s[j] && dp[i+1][j−1], filled from short spans to long: O(n²) time, O(n²) space — strictly worse than expanding from the center, which computes the same thing one diagonal at a time in O(1). So DP doesn't help here. It's taught on this problem because the recurrence is what generalizes: drop "contiguous" (Longest Palindromic Subsequence, 516) and there's no center to expand from, or need "is s[i..j] a palindrome?" answered instantly for thousands of pairs (Palindrome Partitioning, 131) and you precompute the table once. Two pointers as a solve, DP as a lesson.

Complexity

approach time space
brute force · every substring, scan eachO(n³)O(1)
expand around centerO(n²)O(1)
2D DP tableO(n²)O(n²)
Manacher's · nobody expects itO(n)O(n)

Edge cases