All problems
0257MediumStringDynamic Programming

Longest Mirrored Card Run

Tracked in this browser only
Write code

Trains the technique from

LeetCode 516Longest Palindromic Subsequence

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A curator has a rail of exhibit cards. The string cards gives one lowercase letter per card, in the order the cards sit on the rail; the letter is the card's category.

The curator may lift any cards off the rail, including none of them, but may not shuffle the ones left behind, which keep their original order. Call what is left a run, and call a run mirrored when reading it left to right gives the same letters as reading it right to left.

Return the number of cards in the longest mirrored run the curator can leave on the rail. A run of one card is mirrored, so the answer is at least 1.

Examples

Example 1

Input
cards = "abxcba"
Output
5

Lifting the c leaves a, b, x, b, a on the rail, which reads the same from either end, so 5 cards stay.

Example 2

Input
cards = "abab"
Output
3

Lifting the last b leaves a, b, a on the rail, which reads the same from either end, so 3 cards stay.

Example 3

Input
cards = "aabbaa"
Output
6

The rail already reads the same in both directions, so the curator lifts nothing and all 6 cards stay.

Constraints

  • 1 <= cards.length <= 1000
  • cards consists of lowercase English letters only

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def mirrored_run(cards: str) -> int:
Java
public int mirroredRun(String cards)
September 7
Apply