0:00 / 0:00

Count every palindrome hiding in a string. Pick each centre, letter or gap, and expand outward while both ends match, one count per step.

▼

The problem

LeetCode 647 (Medium). Given a string s, return how many of its substrings are palindromes (read the same forwards and backwards). Substrings at different positions count separately, even when their letters are the same.

Examples (LeetCode's): "abc" → 3 (a, b, c) and "aaa" → 6 (a, a, a, aa, aa, aaa).

TRY IT ON LEETCODE ▶

The solution

def countSubstrings(s):
    count = 0
    for c in range(2 * len(s) - 1):
        l, r = c // 2, (c + 1) // 2
        while l >= 0 and r < len(s) and s[l] == s[r]:
            count += 1
            l -= 1
            r += 1
    return count

Transcript

Palindromic Substrings. A palindrome reads the same forwards and backwards, like A B A. Given a string, count how many of its substrings are palindromes. Copies at different positions count separately.

In A B C, only the three single letters count, so the answer is three. A A A has three single A's, two A A's, and A A A itself: six.

The naive way checks every substring: about n squared over two of them, at up to n letters each. That's order n cubed, and most of that work is repeated.

Flip it around. Every palindrome mirrors outward from a center. So pick a center and expand: step left and right together, and while the new ends match, count one more. In A A B A A, the center B gives B, then A B A, then A A B A A, in one sweep. Each step compares just two letters, because the inside already matched. Even lengths like A A center on a gap, so centers sit on every letter and every gap: two n minus one.

In code, loop over the centers. Left and right start on one letter, or on the two letters beside a gap. While both are in bounds and the letters match, add one, then step outward.

Try A B B A. The first A counts one. The gap between A and B fails at once. The first B counts one, then A and B differ. The middle gap matches B B, then A B B A: two more. The second B counts one, the last gap fails, and the final A counts one. Six in all.

Worst case, one letter repeated, every center keeps expanding: two n minus one centers, each up to n over two steps. That's order n squared time, and constant space for two indices and a count. A dynamic programming table finds the same palindromes, but needs a cell for every pair of ends: order n squared space.

Pick a center, expand while the ends match, and count every step. That's Palindromic Substrings.