KatInterview

Maximum Length of Mirror Subsequence

Dynamic ProgrammingAuto-graded · 23 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingstringssubsequences

Last updated

Tests dynamic programming on strings to find the longest subsequence that is identical when reversed.

You are given a string s. Your task is to find the length of the longest subsequence of s that reads the same forwards and backwards.

A subsequence is derived by deleting zero or more characters from the original string without changing the order of the remaining characters. For example, "ace" is a subsequence of "abcde", but "aec" is not.

A string reads the same forwards and backwards if reversing it produces an identical string.

Write a function that computes this maximum length.

Constraints

  • 1 ≤ len(s) ≤ 2000
  • s consists of lowercase English letters only

Examples

Example 1

Input: max_mirror_subsequence_length('bbbab')

Output: 4

Example 2

Input: max_mirror_subsequence_length('cbbd')

Output: 2

Hints

Hint 1

Think about comparing characters at both ends of any substring and how they relate to the inner portion.

Hint 2

Define a subproblem over intervals: what is the answer for substring s[i..j]? How do the endpoints s[i] and s[j] affect the solution?

Hint 3

When the endpoints match, they can both be included. When they differ, at least one must be excluded. This leads to a recurrence relation.