CodeArchon

medium1-D Dynamic ProgrammingAmazonMicrosoftFacebook

Longest Mirror Substring

A text editor highlights the longest contiguous slice of a string that reads identical forwards and backwards.

Given a string s, return the longest palindromic substring in s.

Choose approach

b
0
a
1
b
2
a
3
d
4
ilo
1/5
Narrationstep 1 of 5

Expand center 0; best = "b" (len 1).

1def longestPalindrome(s):
2 best = ""
3 def expand(l, r):
4 while l >= 0 and r < len(s) and s[l] == s[r]:
5 l -= 1; r += 1
6 return s[l+1:r]
7 for i in range(len(s)):
8 for cand in (expand(i, i), expand(i, i+1)):
9 if len(cand) > len(best): best = cand
10 return best
Variables
center=0
best=b
len=1

How to think about it

  1. 2n − 1 candidate centers.
  2. Each expansion is O(n) worst-case.

Edge cases to catch in interview

  • All equal chars -> whole string.
  • No palindrome > 1 -> first char.

Examples

Example 1"bb"
{"s":"cbbd"}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed