DSA Factory
Free Strings lessonsStrings · Stage 5 · Mastery · Step 3

Longest mirror inside

The longest stretch of a string that reads the same both ways. About 14 minutes.

Inward, or outward?

So far you've checked palindromes by walking inwards from both ends. But here you don't know where the ends are. You only know that every palindrome has a middle somewhere.

So which way could your two fingers walk if they started from a middle? And what kinds of middle are there: a single character, or the gap between two?

Two kinds of middle: a character, or the gap between two.
s = "babad", expanding outward from each middle
b
0
a
1
b
2
a
3
d
4
leftright
best
"b"

Middle at 0: 'b' alone. Nothing to its left, so it can't grow. Length 1.

Move 1 of 5
Quick check

Starting at the middle of "racecar" (the e), how far do matching pairs extend outward?

  1. ATo both ends
  2. BOne step
  3. CNot at all
Show the answer

To both ends. c/c, a/a, r/r all match, so the whole word is a palindrome.

Your problem

Longest mirror inside

Return the longest run of consecutive characters of s that reads the same forwards and backwards. If several are equally long, return the one that starts first.

Example
s = "babad" → "bab"

0 ≤ length ≤ 2,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve