Palindromic Substrings
MediumNeetCode 150 1-D Dynamic ProgrammingNetskopePure StorageCitadelProblem
Given a string s, return how many of its substrings are palindromes.
A substring is a run of consecutive letters. Two substrings at different positions count separately even when they spell the same word.
Constraints
- 1 ≤ s.length ≤ 10
- s has lowercase English letters
Examples: pick one to animate
Solutions
TimeO(n²)
SpaceO(1)
Time: There are 2n - 1 centres and each expands over at most n letters.
Space: Only a few counters are used.
Every palindrome has a centre: a letter (odd length) or the gap between two letters (even length).
For each index try both centres and push lo left and hi right while the two
letters match. Every match is one more palindrome, so count it and widen. Add up all the counts.