1. Expand outward
Grow the palindrome while the mirrored characters match.
while (left >= 0 && right < s.length && s[left] === s[right])Typorithm · medium
Step 1 of 8 · intro card
String Algorithms
Expand around every center (odd and even) and keep the longest mirrored span you find.
Every palindrome has a center: a single character (odd) or a gap between two (even).
From each center, expand outward while the characters mirror, recording the longest span.
Trying both center types at each index covers all palindromes in O(n^2).
Centers are odd (i) and even (i, i+1).
Expand while mirrored chars match.
Track the longest span.
function longestPalindrome(s) {
let start = 0;
let maxLen = 0;
function expand(left, right) {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left -= 1;
right += 1;
}
return right - left - 1;
}
for (let i = 0; i < s.length; i += 1) {
const len = Math.max(expand(i, i), expand(i, i + 1));
if (len > maxLen) {
maxLen = len;
start = i - Math.floor((len - 1) / 2);
}
}
return s.slice(start, start + maxLen);
}Connect each part of the code to the concept before you type.
Grow the palindrome while the mirrored characters match.
while (left >= 0 && right < s.length && s[left] === s[right])After the loop overshoots by one on each side, the span is right - left - 1.
return right - left - 1Try an odd center at i and an even center between i and i+1.
const len = Math.max(expand(i, i), expand(i, i + 1))Derive the substring's start index from the center and length.
start = i - Math.floor((len - 1) / 2)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText babad
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state