1088. Palindromes in Linear Time

A word-game designer wants to know how rich a lowercase string s is in palindromes, strings that read the same from left to right and from right to left. Pieces are counted by position: two pieces that spell the same word but start at different indices are different pieces.

Return the number of pairs (i, j) with 0 <= i <= j < s.length such that the substring s[i..j] is a palindrome. Every single letter counts. For instance, "kayak" has 7 such pieces: five single letters, "aya" and "kayak".

The answer can be much larger than the length of the string (a string of one repeated letter has about n squared / 2 palindromic pieces), so use a 64-bit result. Growing a palindrome outward from every centre takes too long on adversarial inputs.

Example 1

Input:
s = "aaa"
Output:
6
Explanation:

The palindromic pieces are a, a, a (three singles), aa, aa (two pairs) and aaa, six in total even though they are all built from the same letter.

Example 2

Input:
s = "abc"
Output:
3
Explanation:

Only the three single letters read the same in both directions.

Example 3

Input:
s = "abba"
Output:
6
Explanation:

The four single letters, the middle pair "bb" and the whole word "abba" make six.

Constraints

1 ≤ s.length ≤ 3 * 105

s consists of lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…