Palindromic Substrings - Problem

Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward. A substring is a contiguous sequence of characters within the string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abc"
Output: 3
💡 Note: Three palindromic substrings: "a", "b", "c". Each single character is a palindrome.
Example 2 — With Longer Palindromes
$ Input: s = "aaa"
Output: 6
💡 Note: Six palindromic substrings: "a", "a", "a", "aa", "aa", "aaa". Multiple overlapping palindromes exist.
Example 3 — Mixed Palindromes
$ Input: s = "aba"
Output: 4
💡 Note: Four palindromic substrings: "a" at index 0, "b" at index 1, "a" at index 2, and "aba" spanning the whole string.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Palindromic Substrings INPUT String s = "abc" a index 0 b index 1 c index 2 All Substrings: "a" "b" "c" "ab" "bc" "abc" Input String s = "abc" ALGORITHM STEPS 1 Expand from Center Try each char as center 2 Check Odd Length Single char centers 3 Check Even Length Between char centers 4 Count Palindromes Sum all valid matches Center Expansion: a OK b OK c OK Even: 0 Palindrome Count Odd: 3 + Even: 0 = 3 FINAL RESULT Palindromic Substrings Found: "a" reads same forward/backward "b" reads same forward/backward "c" reads same forward/backward "ab", "bc", "abc" - NOT palindromes Output 3 Key Insight: The expand-around-center technique achieves O(n^2) time complexity by treating each character and each gap between characters as a potential palindrome center. Every single character is itself a palindrome, so minimum count equals string length. For "abc": 3 single-char palindromes. TutorialsPoint - Palindromic Substrings | Optimal Solution (Expand Around Center)
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
285.0K Views
High Frequency
~15 min Avg. Time
8.5K 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