Skip to content
MediumStringsAI interview only

Palindromic Substrings

Asked atmetaamazongooglemicrosoftlinkedin

01 · Problem

Given a string s, return the number of its substrings that are palindromes (read the same forwards and backwards).

A substring is a contiguous, non-empty block of characters. Substrings are counted by position, not by content: two substrings with the same letters but different start or end indices are counted separately. Every single character is a palindrome on its own.

02 · Examples

Example 01
Input
s = "xyz"
Output
3

The palindromic substrings are "x", "y" and "z".

Example 02
Input
s = "bbb"
Output
6

The palindromic substrings are "b", "b", "b", "bb", "bb" and "bbb" — each occurrence counts separately.

Example 03
Input
s = "abba"
Output
6

The palindromic substrings are "a", "b", "b", "a", "bb" and "abba".

03 · Constraints

  • 011 <= s.length <= 1000
  • 02s consists of lowercase English letters
  • 03Substrings at different positions are counted separately even if they contain the same characters

04 · Optimal complexity

Time
O(n^2)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.