Python coding

Count the palindromes inside a string

Given a string s, return how many of its substrings are palindromes: they read the same left to right and right to left. A substring is a contiguous, non-empty piece of s. Pieces at different positions count separately even when their text is equal, and a single character is a palindrome by itself.

Every character matters, spaces included, and uppercase and lowercase letters are different. s has 0 to 1,000 characters. Aim for O(n²) time.

  • count_palindromes("abc") → 3
  • count_palindromes("aaa") → 6
  • count_palindromes("noon") → 6
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Let pal[i][j] say whether s[i..j] is a palindrome. It is exactly when s[i] == s[j] and the inside, s[i+1..j-1], is a palindrome too.

Hint 2

Stretches of length 1 and 2 have no inside: matching ends are enough. Fill the starts from right to left, so every inside is known before you need it.

Hint 3

One row is enough: for start i, walk j from the right end down to i, and pal[j - 1] still holds the answer for start i + 1.

Solution and why it works
pythonO(n²) · O(n)
def count_palindromes(s: str) -> int:
    n = len(s)
    pal = [False] * n                    # pal[j]: is s[i..j] a palindrome, for the current start i
    count = 0
    for i in range(n - 1, -1, -1):       # later starts first: their stretches are the insides
        for j in range(n - 1, i - 1, -1):    # right to left, so pal[j - 1] still holds start i + 1
            pal[j] = s[i] == s[j] and (j - i < 2 or pal[j - 1])
            count += pal[j]
    return count

s[i..j] is a palindrome exactly when its ends match and s[i+1..j-1] is one, so each of the ~n²/2 stretches costs O(1) once the shorter ones are known. Reversing every substring to compare it re-reads its letters: O(n³). Traps: stretches of length 1 and 2 have no inside to look up, and equal text at different positions counts twice ("aaa" has 6). Expanding outward from each of the 2n − 1 centers walks the same recurrence in O(1) space.

Related lab: Big-O growth