CodeArchon

medium1-D Dynamic ProgrammingFacebookAmazon

Palindrome Counter

A linguistics tool counts every mirror-reading slice (overlapping allowed) in a text sample.

Given a string, return the number of palindromic substrings in it (including duplicates at different positions).

Choose approach

a
0
a
1
a
2
i
1/3
Narrationstep 1 of 3

Center 0: 1 odd + 1 even palindromes. Total = 2.

1def countSubstrings(s):
2 count = 0
3 def expand(l, r):
4 nonlocal count
5 while l >= 0 and r < len(s) and s[l] == s[r]:
6 count += 1; l -= 1; r += 1
7 for i in range(len(s)):
8 expand(i, i); expand(i, i + 1)
9 return count
Variables
i=0
count=2
odd=1
even=1

How to think about it

  1. 2n − 1 centers.
  2. Each successful mirror match counts +1.

Edge cases to catch in interview

  • Empty -> 0.
  • All same chars -> n(n+1)/2.

Examples

Example 13
{"s":"abc"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed