DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 647: Palindromic Substrings — Step-by-Step Visual Trace

Medium — String | Two Pointers | Expand Around Centers | Palindrome

The Problem

Count the total number of palindromic substrings in a given string, where a palindromic substring reads the same forwards and backwards.

Approach

Use the expand around centers technique by checking every possible center position in the string. For each position, expand outward while characters match to count palindromes of both odd and even lengths.

Time: O(n²) · Space: O(1)

Code

class Solution:
    def countSubstrings(self, s: str) -> int:
        def expandAroundCenter(left: int, right: int) -> int:
            count = 0
            # Expand around the center while the characters at both ends are equal.
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
                count += 1
            return count

        if not s:
            return 0

        total_palindromes = 0

        for i in range(len(s)):
            # Check for odd-length palindromes.
            total_palindromes += expandAroundCenter(i, i)

            # Check for even-length palindromes.
            total_palindromes += expandAroundCenter(i, i + 1)

        return total_palindromes
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)