Skip to content

Count Palindromic Substrings

MediumPython 3StringsTwo pointers

You are given a string s. Return the number of non-empty contiguous substrings of s that are palindromes. Substrings that occupy different positions are counted separately even if they are identical in text, and every single character counts as a palindrome of length 1.

Constraints:
  - 0 <= len(s)
  - s consists of arbitrary characters (comparison is exact/case-sensitive)
Examples:
  "abc"    -> 3   ("a", "b", "c")
  "aaa"    -> 6   ("a"x3, "aa"x2, "aaa")
  "aba"    -> 4   ("a", "b", "a", "aba")
  "abccba" -> 9   (6 singles + "cc" + "bccb" + "abccba")
  ""       -> 0
  "a"      -> 1

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…