Typorithm · medium

Longest Palindrome

▷ Interactive algorithm lablongest-palindromestring-algorithmsexpand-centerodd-evensubstring
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Longest Palindrome

0%

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).

Preparing algorithm lab…
01

Centers are odd (i) and even (i, i+1).

02

Expand while mirrored chars match.

03

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);
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Expand outward

Grow the palindrome while the mirrored characters match.

while (left >= 0 && right < s.length && s[left] === s[right])

2. Measured length

After the loop overshoots by one on each side, the span is right - left - 1.

return right - left - 1

3. Odd and even

Try 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))

4. Recover start

Derive the substring's start index from the center and length.

start = i - Math.floor((len - 1) / 2)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Longest Palindrome: Visual Walkthrough & Practice · Typorithm | ApplyDjinn