All problems
0677HardStringDynamic Programming

Fewest Tiles to Mirror the Strip

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1312Minimum Insertion Steps to Make a String Palindrome

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 mosaic strip is written as strip, one lowercase letter per tile, read left to right. Each letter names a tile colour.

In one step you may buy a tile of any colour and slide it into the strip at any position: in front of the first tile, between two neighbouring tiles, or after the last tile. Tiles already on the strip are never removed and never change their order.

A strip is mirrored when the colours read from left to right are the same as the colours read from right to left.

Return the fewest steps needed to leave the strip mirrored.

Examples

Example 1

Input
strip = "cobalt"
Output
5

Buying five tiles gives `tlabocobalt`, which reads the same in both directions and keeps the six original tiles in their original order.

Example 2

Input
strip = "aaab"
Output
1

One bought tile is enough: sliding a `b` in front gives `baaab`, which reads the same both ways.

Example 3

Input
strip = "ggrgg"
Output
0

This strip already reads the same in both directions, so no tile is bought.

Constraints

  • 1 <= strip.length <= 500
  • strip consists of lowercase English letters.

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 fewest_inserts(strip: str) -> int:
Java
public int fewestInserts(String strip)
September 7
Apply