</>

5. Longest Palindromic Substring

Medium NeetCode 150
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
1-D Dynamic Programming
Time
—
Space
—

Standard Solution (C++)

SummaryGiven a string, find and return the longest contiguous substring that reads the same forwards and backwards; if multiple palindromes tie for longest, any one of them is acceptable.

Approach
  • Use the expand-around-center technique: for each index, treat it as the center of a potential palindrome and grow outward as long as characters match.
  • Handle both odd-length palindromes (single-character center) and even-length palindromes (two-character center) at every index.
  • Track the best start position and length seen so far, updating whenever a longer palindrome is found.
  • This avoids the O(n²) space of a full DP table while achieving the same O(n²) time — each of the n centers costs at most O(n) expansion steps.
#include <string>
#include <algorithm>
using namespace std;

class Solution {
    // Expands outward from [lo, hi] and returns the length of the palindrome found.
    int expand(const string& s, int lo, int hi) {
        while (lo >= 0 && hi < (int)s.size() && s[lo] == s[hi]) {
            --lo;
            ++hi;
        }
        // After the loop, s[lo+1..hi-1] is the palindrome.
        return hi - lo - 1;
    }

public:
    string longestPalindrome(string s) {
        int bestStart = 0, bestLen = 1;

        for (int i = 0; i < (int)s.size(); ++i) {
            // Odd-length palindrome centered at i.
            int odd  = expand(s, i, i);
            // Even-length palindrome centered between i and i+1.
            int even = expand(s, i, i + 1);

            int len = max(odd, even);
            if (len > bestLen) {
                bestLen   = len;
                // Recover start: for a palindrome of length len centered near i,
                // the left edge is i - (len - 1) / 2.
                bestStart = i - (len - 1) / 2;
            }
        }

        return s.substr(bestStart, bestLen);
    }
};
Time O(n²) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <algorithm>
#include <string>
using namespace std;

class Solution {
public:
  int expandAroundCenter(const string &s, int leftIdx, int rightIdx) {
    int strLen = s.length();
    while (leftIdx >= 0 && rightIdx < strLen && s[leftIdx] == s[rightIdx]) {
      leftIdx--;
      rightIdx++;
    }
    return rightIdx - leftIdx - 1;
  }
  string longestPalindrome(string s) {
    // there are two types of palindrome, odd-length and even-length
    int strLen = s.length();
    int maxLen = 1;
    int startOfMaxLen = 0;

    for (int i = 0; i < strLen; i++) {
      int len1 = expandAroundCenter(s, i, i);
      int len2 = expandAroundCenter(s, i, i + 1);
      int curLen = max(len1, len2);
      if (curLen > maxLen) {
        maxLen = curLen;
        startOfMaxLen = i - (curLen - 1) / 2;
      }
    }

    return s.substr(startOfMaxLen, maxLen);
  }
};

// Time: O(n^2)
// Space: O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern