Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Count the palindromic substrings

Medium · Target 15 minutes · Dynamic programming · Type asked atMetaAmazon

Given a string s, return the number of its substrings that are palindromes. Substrings at different positions count separately even if they are equal.

Examples

InputOutputWhy
s = "abc"3"a", "b", "c".
s = "aaa"6Three "a", two "aa", one "aaa".
s = "abba"6a, b, b, a, bb, abba.

Constraints

  • 1 ≤ s.length ≤ 1000
  • Lowercase English letters

Hints

Hint 1

pal[i][j] = s[i] = s[j] and (j − i < 2 or pal[i + 1][j − 1]); count the true entries.

Hint 2

Or expand from each of the 2n − 1 centres: every step that keeps the ends equal is one more palindrome.

Where people lose marks

  • Counting distinct palindromes instead of positions.
  • Forgetting even-length centres.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.