Longest Mirror Piece

Medium · 2-D & String DP · about 25 min

A word puzzle asks for the longest run of neighbouring letters inside a string s that reads the same forwards and backwards (like "level" or "abba").

Return that run. If several runs have the same longest length, return the one that starts first (smallest start index). For an empty string return "".

  • 0 <= len(s) <= 1000, lowercase letters only.

Examples:

longest_mirror_piece("babad") → "bab" ("aba" is just as long but starts later)

longest_mirror_piece("cbbd") → "bb"

Hints

  • A mirror piece stays a mirror when you peel off its two end letters.
  • So every mirror piece can be grown from its middle, one letter on each side at a time.
  • Odd-length pieces have a middle letter; even-length pieces have a middle gap. Try both kinds of centre.

Learn the pattern first: the 2-D & String DP lesson.

More 2-D & String DP problems