Palindromic Substrings - Problem
Count Palindromic Substrings

Given a string s, return the total number of palindromic substrings contained within it.

A palindrome is a string that reads the same forwards and backwards (like "racecar" or "aba"). A substring is any contiguous sequence of characters within the original string.

For example, in the string "abc", we have substrings: "a", "b", "c", "ab", "bc", "abc". Among these, only "a", "b", and "c" are palindromes, so the answer is 3.

Your task: Count all palindromic substrings efficiently!

Input & Output

example_1.py โ€” Basic case
$ Input: s = "abc"
โ€บ Output: 3
๐Ÿ’ก Note: Three palindromic substrings: "a", "b", "c". Each single character is a palindrome by definition.
example_2.py โ€” Multiple palindromes
$ Input: s = "aaa"
โ€บ Output: 6
๐Ÿ’ก Note: Six palindromic substrings: "a" (3 times), "aa" (2 times), "aaa" (1 time). Total = 3 + 2 + 1 = 6.
example_3.py โ€” Mixed palindromes
$ Input: s = "aba"
โ€บ Output: 4
๐Ÿ’ก Note: Four palindromic substrings: "a" (at index 0), "b", "a" (at index 2), and "aba". The entire string is also a palindrome.

Visualization

Tap to expand
๐Ÿชž Mirror Pattern DetectionString: "abccba" - Find all palindromic substringsabccbacCenter at first 'c': finds "c"ccCenter between c's: finds "cc"bccbExpand further: finds "bccb"abccbaFull expansion: finds "abccba"Single chars: 6Two chars: 1 (cc)Four chars: 1 (bccb)Six chars: 1 (abccba)Total: 9 palindromes๐Ÿ’ก Key: Each position can be center of multiple nested mirror patterns
Understanding the Visualization
1
Single tile mirrors
Every single tile is a perfect mirror by itself
2
Expand from center
From each tile, check if expanding left and right creates mirror patterns
3
Check dual centers
Also check if adjacent tiles can form the center of an even-length mirror
4
Count all patterns
Sum up all valid mirror patterns found
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking every substring individually, expand around each potential center point. This naturally finds all palindromes while avoiding redundant work - like ripples expanding from stones dropped in water!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยณ)

O(nยฒ) for generating all substrings ร— O(n) for checking each palindrome

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 1000
  • s consists of lowercase English letters only
  • A single character is always considered a palindrome
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 24 Apple 18
89.2K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen