</>

647. Palindromic Substrings

Medium NeetCode 150
1-D Dynamic Programming Time O(N^2) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
1-D Dynamic Programming
Time
O(N^2)
Space
O(1)

Standard Solution (C++)

SummaryCount the total number of palindromic substrings in a given string, where every individual character counts as a palindrome and longer palindromes can overlap.

Approach
  • Use the expand-around-center technique: every palindrome has a center — either a single character (odd length) or a pair of identical characters (even length).
  • For each of the n possible odd centers and n-1 possible even centers, expand outward while the boundary characters match, incrementing the count for each valid palindrome found.
  • This avoids the O(n²) space of a DP table while achieving the same O(n²) time by exploiting the nested symmetry of palindromes.
#include <string>
using namespace std;

class Solution {
    // Expand from center [l, r] and return the number of palindromic substrings found.
    int expandCount(const string& s, int l, int r) {
        int count = 0;
        while (l >= 0 && r < (int)s.size() && s[l] == s[r]) {
            ++count;
            --l;
            ++r;
        }
        return count;
    }

public:
    int countSubstrings(string s) {
        int total = 0;
        for (int i = 0; i < (int)s.size(); ++i) {
            total += expandCount(s, i, i);     // odd-length centers
            total += expandCount(s, i, i + 1); // even-length centers
        }
        return total;
    }
};
Time O(n²) Space O(1)

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

My Solution (C++)

#include <string>
using namespace std;

class Solution {
public:
    int expand(const string& s, int l, int r){
        int count=0;
        while(l>=0 && r<s.length() && s[l]==s[r]){
            ++count;
            --l;
            ++r;
        }
        return count;
    }
    int countSubstrings(string s) {
        int count=0;
        int len=s.length();
        for(int i=0; i<len; ++i){
            count+=expand(s, i, i);
            count+=expand(s, i, i+1);
        }
        return count;
    }
};

// Time Complexity: O(N^2)
// Space Complexity: O(1)
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