Maximum Length of Mirror Subsequence
Dynamic ProgrammingAuto-graded · 23 test casesLast 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) ≤ 2000sconsists 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
We solve this using interval dynamic programming. Define M(i, j) as the maximum length of a mirror subsequence within the substring s[i..j].
The key insight comes from examining the characters at positions i and j:
Case 1: Characters match (s[i] == s[j])
When the endpoints are identical, we can include both in our mirror subsequence. They form the outer layer, wrapping around whatever mirror subsequence exists in the interior s[i+1..j-1]. This gives us:
M(i, j) = M(i+1, j-1) + 2
Case 2: Characters differ (s[i] != s[j])
A mirror subsequence cannot simultaneously start with s[i] and end with s[j] since its first and last characters must match. Therefore, at least one endpoint must be excluded. We take the better of two options:
M(i, j) = max(M(i+1, j), M(i, j-1))
Base cases:
M(i, i) = 1: a single character is always a mirrorM(i, j) = 0wheni > j: empty intervals contribute nothing
The answer is M(0, n-1).
Why This Works
Consider any optimal mirror subsequence within s[i..j]. If the endpoints match, we can always construct an equally good solution that uses both (or improve if we weren't using both). Removing this matching pair leaves a smaller mirror subsequence in the interior. If the endpoints differ, the optimal solution must lie entirely within either s[i+1..j] or s[i..j-1], since we cannot use both mismatched endpoints as the outer layer of a mirror. This exhaustive case analysis, combined with the fact that each recursive call strictly shrinks the interval, proves correctness by induction on interval length.
Space-Optimized Implementation
While a 2D table works, we can optimize to O(n) space. Each row i only depends on row i+1 (the cells "below") and the current row being filled (cells to the "left"). We maintain a single array where dp[j] represents the answer for the interval currently being processed. As we sweep through positions, we track the diagonal value from the previous row in a temporary variable, allowing us to overwrite cells in place.
Time Complexity: O(n²) — we process each of the O(n²) interval pairs once
Space Complexity: O(n) — single array storage
Solution Code
def max_mirror_subsequence_length(s: str) -> int:
n = len(s)
dp = [1] * n
for i in range(n - 2, -1, -1):
diagonal = 0
for j in range(i + 1, n):
below = dp[j]
if s[i] == s[j]:
dp[j] = diagonal + 2
else:
dp[j] = max(dp[j], dp[j - 1])
diagonal = below
return dp[-1] if n else 0