Longest Palindromic Substring solution explained

To find the longest palindromic substring, treat every character and every gap between two neighbors as a possible center, and expand outward while the characters on both sides match. A string of length n has 2n - 1 centers and each expansion costs at most O(n), so the solution runs in O(n²) time with O(1) extra space. A dynamic programming table gets the same time with O(n²) memory, and Manacher's algorithm reaches O(n) if the interviewer pushes.

By Published 7 min read

The task, restated

Given a string, return the longest unbroken slice of it that is a palindrome, the same read left to right and right to left. The slice must be contiguous. Picking scattered letters that happen to form a palindrome is a different problem, the longest palindromic subsequence. A single character always counts, so any non-empty string has an answer of length at least 1.

Examples made up for this page
InputA longest palindromeLengthCenter
tacocatztacocat7The c in the middle (odd length)
noondaynoon4The gap between the two o's (even length)
kayakskayak5The y
levelheadedlevel5The v
abcda (or b, c, d)1Any single letter; ties are fine
Examples made up for this page. Scroll sideways on a small screen.

Clarify the character set, whether case matters, and what to return on ties and on an empty string. Most versions treat the input as plain lowercase letters or ASCII and accept any longest answer.

What the interviewer is checking

This is a string problem that rewards one structural insight: every palindrome has a middle, and it grows outward symmetrically from it. Interviewers want you to move from checking every substring to expanding from middles, and they watch closely for the even-length case. Code that only expands from single characters will return a single letter for noonday instead of noon. Being able to mention, without coding, that a DP table and Manacher's algorithm exist shows range without wasting time.

Brute force: try lengths from longest down

List substrings from longest to shortest and return the first palindrome. Checking a slice costs O(n), there are O(n²) slices, so the worst case is O(n³). Trying long lengths first means strings with a long palindrome finish early, but a string with no repeats still checks everything.

def widest_mirror_slow(text):
    n = len(text)
    for size in range(n, 0, -1):
        for start in range(n - size + 1):
            piece = text[start : start + size]
            if piece == piece[::-1]:
                return piece
    return ""
Longest-first search, O(n³) worst case. Useful as a test reference.

Optimal in practice: expand around every center

Stand at a center and step outward one character on each side at a time, stopping when the two characters differ or you fall off an end. What you have at that point is the longest palindrome with that center. Do this for the n single-character centers, which give odd lengths, and the n - 1 gaps, which give even lengths. Keep the widest result. Each expansion is at most O(n), and in typical text it stops after a step or two.

def widest_mirror(text):
    if not text:
        return ""

    def reach(left, right):
        while left >= 0 and right < len(text) and text[left] == text[right]:
            left -= 1
            right += 1
        return left + 1, right  # slice bounds of the palindrome found

    best_lo, best_hi = 0, 1
    for mid in range(len(text)):
        for lo, hi in (reach(mid, mid), reach(mid, mid + 1)):
            if hi - lo > best_hi - best_lo:
                best_lo, best_hi = lo, hi
    return text[best_lo:best_hi]
Python: expand from 2n - 1 centers, O(n²) time, O(1) extra space.
function widestMirror(text) {
  if (text.length === 0) return "";
  const reach = (left, right) => {
    while (left >= 0 && right < text.length && text[left] === text[right]) {
      left--;
      right++;
    }
    return [left + 1, right];
  };
  let bestLo = 0;
  let bestHi = 1;
  for (let mid = 0; mid < text.length; mid++) {
    for (const [lo, hi] of [reach(mid, mid), reach(mid, mid + 1)]) {
      if (hi - lo > bestHi - bestLo) {
        bestLo = lo;
        bestHi = hi;
      }
    }
  }
  return text.slice(bestLo, bestHi);
}
JavaScript: the same expansion with slice bounds.

Returning bounds rather than building strings inside the loop matters: slicing a new string at every center would add O(n) work per center for no reason. Only the final slice is built. When the even-length call starts with mid + 1 past the end, the loop condition fails at once and it returns an empty range, so no extra check is needed.

The DP table, in words

A slice from i to j is a palindrome when its two end characters match and the slice from i + 1 to j - 1 is a palindrome, or is shorter than two characters. Filling a boolean table by increasing length applies that rule to every slice in O(n²) time. It uses O(n²) memory, which is why the center expansion is usually preferred for this problem. The table becomes more useful when you need the answer for many slices, such as counting all palindromes or splitting a string into palindromes.

If they ask for linear time

Manacher's algorithm computes the radius of the palindrome at every center in O(n) total by reusing the mirror image of radii already found inside the current rightmost palindrome. It is rarely expected in full, but naming it and sketching the mirror idea is a good answer to 'can you do better?'. If you choose to write it, insert a separator between characters so odd and even centers become the same case.

Time and space

Cost for a string of length n
VersionTimeExtra space
Every substring, longest firstO(n³) worst caseO(n) for the slice being checked
DP table of slicesO(n²)O(n²)
Expand around 2n - 1 centersO(n²) worst caseO(1) besides the answer
Manacher's algorithmO(n)O(n)
Cost for a string of length n. Scroll sideways on a small screen.

The worst case for center expansion is a string of one repeated letter, where nearly every expansion runs to an edge.

Edge cases

  • Empty string: return an empty string, or whatever the interviewer specifies.
  • One character: that character.
  • No repeated letters: any single character.
  • The whole string is a palindrome, odd or even length.
  • A repeated letter such as zzzzzz: the whole string, and the slowest case for the expansion.
  • Unicode beyond basic letters: indexing by code unit in JavaScript can split some characters, so ask if that matters.

Mistakes to avoid

  • Expanding only from characters, which misses every even-length palindrome.
  • Confusing substring with subsequence and writing an LCS-style DP.
  • Off-by-one on the returned bounds after the loop overshoots by one on each side.
  • Building a new string at every step of every expansion, which quietly adds a factor of n.
  • Reversing the string and taking the longest common substring with the original. It can return a match that is not a palindrome unless you also check the positions line up.

How to explain it out loud

Fictional example

Getting the even case in before you are asked
Candidate
Every palindrome mirrors around a middle. If I stand at each possible middle and walk outward while the letters match, I find the longest one for that middle.
Candidate
Middles can be a letter or the gap between two letters, because noon has no middle letter. So there are 2n minus 1 of them, and each walk is at most n steps.
Candidate
That is quadratic time and constant space. A DP table gives the same time with quadratic memory, and Manacher gets linear time if you want me to sketch it.

Palindromic Substrings counts every palindrome instead of finding the widest, and works well with the DP table described above. Maximum Product Subarray is another search for the best contiguous stretch. Min Cost to Connect All Points switches to graphs, where a greedy choice is provably correct.

Where Natively fits

A good way to practice this one is to explain the center idea aloud before writing a line. Natively runs on Mac and Windows, can pick up the problem from a screenshot and offer an expansion solution to check yours against, and keeps a transcript of the mock so you can confirm you raised the even-length case unprompted. The AI interview assistant page explains how practice sessions work.

Questions people ask

What is the best way to find the longest palindromic substring?

In interviews, expand around centers. Treat each character and each gap between neighbors as a center, grow outward while both sides match, and keep the widest result. It runs in O(n²) time with O(1) extra space.

Why are there 2n - 1 centers?

Odd-length palindromes are centered on a character, giving n centers, and even-length ones are centered on a gap between two characters, giving n - 1. Skipping the gaps misses answers such as noon.

Can the longest palindromic substring be found in O(n)?

Yes, with Manacher's algorithm, which reuses mirrored radii inside the rightmost palindrome found so far. It is rarely required in full, but naming it is a good answer to a follow-up.

Is the dynamic programming solution better than expanding around centers?

Both take O(n²) time, but the DP table needs O(n²) memory while center expansion needs O(1). The table is more useful when you need answers for many slices, such as counting all palindromes.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP