CodingNodes / 1-D Dynamic Programming / Longest Palindromic Substring System design Space play · ←→ step · R restart

Problem

Given a string s, return its longest palindromic substring: a run of consecutive letters that reads the same forwards and backwards.

In every test the longest answer is unique.

Constraints

  • 1 ≤ s.length ≤ 12
  • s has lowercase English letters
  • the longest palindromic substring is unique

Examples: pick one to animate

Solutions

TimeO(n²) SpaceO(1)

Time: There are 2n - 1 centres and each expands over at most n letters.

Space: Only a few integers are kept; the answer is cut from s at the end.

Every palindrome mirrors around a centre: a letter (odd length) or the gap between two letters (even length). For each index try both centres and push lo left and hi right while the two letters match. The window that stopped is hi - lo - 1 long. Keep the longest length and where it starts.