All Blind 75 questions

Palindromic Substrings

FreeDynamic programmingMedium53 of 75

The problem

Count all nonempty contiguous palindromic substrings. Substrings at different positions count separately even when their text is identical.

Example

"aaa" → 6: three length-1, two length-2, and one length-3 substring

Need a hint?

Every successful center expansion discovers one palindrome.

Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.

Notes stay in this browser when storage is available.

Read the solution approach

Try every character as an odd center and every neighboring gap as an even center. While the endpoints match, increment the count and expand both ways. Each substring has one unique center, so nothing is counted twice.

Complexity

O(n²) time and O(1) space.

Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.