↓Skip to main content
  1. LeetCode/

LeetCode 647: Palindromic Substrings

·1 min· ·
LeetCode Medium Two-Pointers String Dynamic-Programming
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-01

  • Submissions: Accepted (first try)

Approach
#

As in LC 5, expand around the 2n - 1 centers (characters and gaps); each step outward with matching ends adds one palindromic substring.

My Attempts
#

Passed on the first try, expanding odd and even centers as in LC 5.

Solution
#

class Solution:
    def countSubstrings(self, s: str) -> int:
        count = 0
        for center in range(2 * len(s) - 1):
            l, r = center // 2, center // 2 + center % 2
            while l >= 0 and r < len(s) and s[l] == s[r]:
                count += 1
                l, r = l - 1, r + 1
        return count

Complexity
#

Time O(n²), space O(1).

Mistakes to Avoid
#

  • Count both odd- and even-length centers.

Interview Explanation
#

I expand around every character and every gap, counting one palindrome for each step outward with matching ends. Time O(n²), space O(1).

Related

LeetCode 5: Longest Palindromic Substring
·2 mins
LeetCode Medium Two-Pointers String Dynamic-Programming Manacher
LeetCode 5 note: expand around centers, using each position as an odd and an even center; with interval DP, iterate i from large to small
LeetCode 131: Palindrome Partitioning
·2 mins
LeetCode Medium String Dynamic-Programming Backtracking
LeetCode 131 note: each level cuts a palindrome from the front of the remaining string, trying every length from 1 to the whole remainder
LeetCode 392: Is Subsequence
·2 mins
LeetCode Easy Two-Pointers String Dynamic-Programming
LeetCode 392 note: two pointers; the pointer on t always advances, and the one on s advances on a match; bound-check both
LeetCode 143: Reorder List
·2 mins
LeetCode Medium Linked-List Two-Pointers Stack Recursion
LeetCode 143 note: find the middle, reverse the second half, and merge the two alternately, cutting the first half’s tail
LeetCode 208: Implement Trie (Prefix Tree)
·2 mins
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 note: each node is a children dict plus an is_end flag; insert, search and startsWith all walk down character by character
LeetCode 287: Find the Duplicate Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 note: treat i -> nums[i] as a linked list; the duplicate is the cycle entry, found with Floyd’s algorithm in O(1) space without modifying the array