806. Longest Mirror Subsequence

Medium3.5 points estimatedStringDynamic Programming3 hints

A jeweller threads coloured beads in the order given by the lowercase string s, one letter per bead colour. She may cut out any beads she likes, leaving the remaining ones in their original order, and wants the leftover necklace pattern to read the same from left to right as from right to left.

Return the largest number of beads that can remain. A single bead always qualifies, so the answer is at least 1 for a non-empty string.

Your solution should run in O(n^2) time, where n is the length of s, and use O(n) extra space.

Example 1

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

The longest subsequence of "bookkeeperz" that reads the same in both directions has length 3.

Example 2

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

The longest subsequence of "synchronize" that reads the same in both directions has length 3.

Example 3

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

The longest subsequence of "mnemonic" that reads the same in both directions has length 3.

Constraints

1 ≤ s.length ≤ 1200

s contains only 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^2)
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…