Palindromic Substrings

MediumStringsexpand around center

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a string s, return the total number of substrings of s that read the same forwards and backwards. A **substring** is a contiguous, non-empty run of characters within the string. Two substrings are counted **separately** if they begin or end at different index positions, even when the characters they contain are identical. In other words, you are counting occurrences by position, not distinct text values. For example, in the string "aaa" the single-character substrings at indices 0, 1, and 2 each count on their own, the two-character substrings s[0..1] and s[1..2] each count, and the full string s[0..2] counts as well — giving 6 palindromic substrings in total. Every individual character is itself a palindrome, so the answer is always at least the length of s.

Examples

Input: s = "abc"
Output: 3
Only the three single-character substrings "a", "b", and "c" are palindromes.
Input: s = "aaa"
Output: 6
The palindromic substrings are "a", "a", "a", "aa", "aa", and "aaa" — each counted by its position.
Input: s = "abba"
Output: 6
The palindromes are the four single characters, plus "bb" and "abba".

Constraints

  • `1 <= s.length <= 1000`
  • `s` consists only of lowercase English letters.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.