oneby7

2-D Dynamic Programming Two strings

570. Count Palindromic Subsequences

Hard

You are given a string s. Count its subsequences that are palindromes.

A subsequence is what is left after deleting some letters of s, without changing the order of the rest. Its letters do not have to sit next to each other. A palindrome reads the same forwards and backwards. A single letter is a palindrome. The empty subsequence does not count.

Subsequences are told apart by the positions they use, not by the word they spell. In "aa", the first a and the second a are two different subsequences, so the answer is 3: a, a and aa.

The count can be very large, so return it modulo 109 + 7.

Example 1

Input: s = "abab"

Output: 8

Explanation: The four single letters, aa (indexes 0 and 2), bb (1 and 3), aba (0, 1, 2) and bab (1, 2, 3).

Example 2

Input: s = "aaa"

Output: 7

Explanation: Every one of the 7 non-empty choices of positions spells a palindrome. aa alone appears 3 times: indexes 0 and 1, 0 and 2, and 1 and 2.

Example 3

Input: s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

Output: 147483633

Explanation: s has 31 copies of a, so all 231 − 1 = 2147483647 non-empty subsequences are palindromes. Modulo 109 + 7 that is 147483633.

Check your understanding

Work out the answer for this input before you write any code.

s = "abaa"

Constraints

  • 1 ≤ s.length ≤ 3000
  • s holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.