Scrivio Interview library
Strings and triesDynamic programmingReported 69 times · 16 min read · updated 15 November 2026

Find the longest substring of a string that reads the same forwards and backwards.

1What a palindrome is, and what the question asks of us

Write a word on a strip of paper and fold the strip at its middle. If every letter lands on a copy of itself, the word is a palindrome, the same forwards and backwards. The word level passes, because the fold falls on the v and the two e letters and the two l letters land on each other. The word lever fails, because the l lands on an r.

Our question gives us one string and asks for its longest substring that is a palindrome. A substring is a run of neighbouring letters taken without skipping any, so in bananas nana is a substring but bnn is not.

Our example is bananas, its letters numbered from 0: b, a, n, a, n, a, s. The answer is anana, the letters from index 1 to index 5. Fold it at the middle a, index 3, and the n letters land on each other, and so do the outer a letters. Banana is longer, but it fails, because its b would land on an a.

Now do it once by hand. Put a finger on each letter in turn and ask how far you can spread out on both sides while the letters keep matching. On the first n you get a, n, a. On the middle a you get n on both sides, then a on both sides, and then b against s, which stops you. That gives anana. You have just done the whole algorithm; the rest of this article only makes that exercise careful.

PictureThe word bananas and its longest palindrome

Indexes are shown above the letters. The marked run is the answer, and its middle letter is index 3.

  1. b0a1n2a3n4a5s6startmidend
    answer
    anana
    length
    5

    1The longest palindrome in bananas is anana, from index 1 to index 5. Folded at the a in index 3, every letter lands on a copy of itself.

What to assume

Do we return the substring or its length?
The substring.
If two palindromes tie, which one?
The first from the left. We compare characters exactly, and an empty string gives an empty string.
And abc, where no two letters match?
A single letter is a palindrome, so the answer is a, the first letter.

A careful candidate asks a few questions first. Do we return the substring or its length? The substring. If two palindromes tie, which one? The first from the left. We compare characters exactly, and an empty string gives an empty string. And abc, where no two letters match? Every single letter folds onto itself, so the answer is a, the first letter.

2How to recognise a grow-from-the-middle string problem

Meeting this question for the first time, most of us picture every possible start and end, check each run with the fold test, and keep the longest. That instinct is sound, and it is the brute force we will write next, but it uses nothing special about palindromes. So let us read the question again and take its clues one at a time.

The first clue is the word substring. A substring is fixed by two numbers, where it starts and where it ends, so a string of n letters has about n times n divided by 2 of them. The clue tells us that our real job is to avoid visiting them one by one.

The second clue is the phrase reads the same forwards and backwards. That is the fold, and a fold has a middle. A run passes exactly when its first and last letters are equal and the part between them is also a palindrome. So anana is one because its outer letters are both a and its inside, nan, is one too. Every palindrome is a smaller palindrome wrapped in a matching pair of letters.

The third clue is the word longest, which means a running best that we update as we go.

Together these clues place the problem in the strings and tries family, questions about the letters of strings. The technique is called expanding around centres. A centre is the middle of a possible palindrome, the place where the paper is folded. Expanding means stepping one letter outward on both sides at a time. The rule to carry to new problems is this: when a property of a range is true only if it is true for the same range with both ends removed, try growing every range outward from its middle instead of listing ranges by start and end.

A few other patterns look tempting but do not fit. A sliding window, a range that moves along the string, needs a condition that changes predictably as it grows, but aba is a palindrome, abab is not and ababa is again. Two pointers moving in from both ends test one run, not many. A trie, a tree of letters that stores many words by their prefixes, helps with a dictionary of words, not one string to fold.

3The honest first attempt, checking every substring

There is nothing wrong with starting from the slow, obvious method; it is easy to trust and its weakness shows the way forward. The honest first attempt is to try every start i and every end j, test the run from i to j with the fold test, and keep the longest run that passes.

The fold test itself is two fingers. Put one finger on the first letter of the run and one on the last, compare them, and if they match, move both fingers one step inward. If the fingers meet or cross without a mismatch, the run is a palindrome. Testing nan this way compares n with n, then the fingers meet on the a, so it passes.

Step throughThe brute force compares the same pair of letters twice

The first frame is the test of anana. The second is the test of nan, which comes later in the loops.

  1. b0a1n2a3n4a5s6ij
    testing
    anana (1 to 5)
    comparisons
    2

    1Testing anana, the run from index 1 to 5, compares a with a and then the n at index 2 with the n at index 4. Both match, so anana passes.

  2. b0a1n2a3n4a5s6ij
    testing
    nan (2 to 4)
    comparisons
    1, repeated

    2Later the loops reach i = 2, j = 4 and test nan. It compares the same two n letters again, work that was already done inside anana.

Java
static String longestBrute(String s) {
String best = "";
for (int i = 0; i < s.length(); i++) // every start
for (int j = i; j < s.length(); j++) // every end
if (isPalindrome(s, i, j) && j - i + 1 > best.length())
best = s.substring(i, j + 1); // a longer palindrome
return best;
}
static boolean isPalindrome(String s, int i, int j) {
while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false; // ends meet inward
return true;
}

Let us count. Bananas has 7 runs of length 1, 6 of length 2, and so on down to 1 of length 7, 28 substrings in all. Running the fold test on all of them makes 22 letter comparisons. That sounds small, because most runs here fail at once, but in aaaaaaaa every fold test walks all the way to the middle.

So for a string of n letters there are about n squared divided by 2 substrings, and each fold test can take about n divided by 2 comparisons. Multiplying them, the work grows like n times n times n, which we write as O(n cubed), read as order n cubed. The extra memory, called the space, is O(1), meaning constant.

Where is the waste? Testing anana compares the outer a letters and then the n letters at index 2 and 4. Later, testing nan compares those same two n letters again. A long run's fold test always repeats the tests of the shorter runs inside it, because it walks in from the outside.

4From the repeated work to growing outward from each centre

A natural first repair for the repeated work is to remember results. Let isPal[i][j] be true when the run from i to j is a palindrome. For a run longer than two, isPal[i][j] is true when the letters at i and j are equal and isPal[i + 1][j - 1] is true. Filling it from short runs to long ones is dynamic programming, building a big answer from smaller ones. It brings the time to O(n squared), but the table holds n times n answers.

But look at which entry each answer needs. To know about the run from 1 to 5 we need the run from 2 to 4, and to know about 2 to 4 we need 3 to 3. All three runs have the same middle, index 3. So a chain of table entries is really one walk outward from one centre, and we need not store it at all.

That is the whole idea. Put a left finger and a right finger on a centre, and while both are inside the string and their letters match, move each one step outward. When they stop, the letters strictly between them form the longest palindrome with that centre. Do this for every centre and keep the best.

A beginner usually asks the next question here. If we put a centre on every letter, have we covered every palindrome? Let us try noonday. Standing on the first o, its neighbours are n and o, which differ, so we find only o. Yet noon is a palindrome. It has an even number of letters, so its fold falls between the two o letters.

Step throughWhy we also need centres between letters

Noon has four letters, so its middle is the gap between index 1 and index 2. Only an even centre can find it.

  1. n0o1o2n3d4a5y6LR
    centre
    on index 1
    length
    1

    1Standing on the first o and stepping outward compares n with the second o. They differ, so an odd centre on this letter finds only o.

  2. n0o1o2n3d4a5y6LR
    centre
    between 1 and 2
    length
    2 so far

    2Now the centre is the gap between index 1 and index 2. Left starts on the first o, right on the second, and they match.

  3. n0o1o2n3d4a5y6LR
    centre
    between 1 and 2
    length
    4 so far

    3One step outward compares the n at index 0 with the n at index 3. They match, so noon reads the same both ways.

  4. n0o1o2n3d4a5y6R
    centre
    between 1 and 2
    length
    4
    start
    1 - (4 - 1) / 2 = 0

    4Left would now be -1, before the start of the word, so the loop stops. The length is right - left - 1 = 4 - (-1) - 1 = 4, the word noon.

So there are two kinds of centre. An odd-length palindrome such as ana has a letter in the middle, so left and right both start on it. An even one such as noon has a gap in the middle, so left starts on one letter and right on the next. There are n letters and n - 1 gaps, so 2n - 1 centres.

Why is this correct? Every palindrome in the string has exactly one middle, either a letter or a gap. Expanding from that middle, the fingers keep matching for as long as the palindrome lasts, and they only step out after a match, so nothing false is reported. Since we try all 2n - 1 middles, the longest palindrome is found from its own middle.

One piece of arithmetic needs care. When the loop stops, left and right have each gone one step too far. So the palindrome lies strictly between them, and its length is right - left - 1. A common slip is to return right - left + 1, which counts the two letters that did not match.

5Watching the centres grow across bananas

The picture plays the method on bananas, centre by centre. For each centre, L and R mark the two letters being compared, the marked letters are the palindrome found so far around that centre, and the panel on the right shows the centre and the best palindrome so far. Watch how the middle a keeps going.

The even centres are tried too, but in bananas no two neighbours are equal, so each fails at its first comparison; the notes mention them rather than drawing them.

Step throughExpanding around each centre of bananas

L and R are the two letters compared at each step. The best palindrome so far is in the panel.

  1. b0a1n2a3n4a5s6c
    centre
    0 (b)
    best so far
    b, length 1

    1Centre 0 is the b. Stepping outward, left falls off the start of the word, so it stops at length 1, and the even centre between b and a fails at once. Best is b.

  2. b0a1n2a3n4a5s6LR
    centre
    1 (a)
    best so far
    b, length 1

    2Centre 1 is the first a. One step outward compares b with n. They differ, so this centre gives only a, length 1, which does not beat b.

  3. b0a1n2a3n4a5s6LR
    centre
    2 (n)
    best so far
    b, length 1

    3Centre 2 is the first n. One step outward compares the a on each side. They match, so a, n, a reads the same both ways and we step out again.

  4. b0a1n2a3n4a5s6LR
    centre
    2 (n)
    best so far
    ana, length 3

    4The next step compares b with the second a. They differ, so the palindrome around centre 2 is ana, length 3, starting at index 1. It becomes the best.

  5. b0a1n2a3n4a5s6LR
    centre
    3 (a)
    best so far
    ana, length 3

    5Centre 3 is the middle a. One step outward compares the n at index 2 with the n at index 4. They match, so we keep going.

  6. b0a1n2a3n4a5s6LR
    centre
    3 (a)
    best so far
    ana, length 3

    6The next step compares the a at index 1 with the a at index 5. They match too, so anana, five letters, reads the same both ways.

  7. b0a1n2a3n4a5s6LR
    centre
    3 (a)
    best so far
    anana, length 5

    7The next step compares b with s. They differ, so centre 3 gives anana, length 5. The start is 3 - (5 - 1) / 2 = 1, and anana becomes the best.

  8. b0a1n2a3n4a5s6LR
    centre
    4 (n)
    best so far
    anana, length 5

    8Centre 4, the second n, matches the a on each side and then meets n against s, which differ. It gives ana, length 3, which does not beat 5.

  9. b0a1n2a3n4a5s6c
    centre
    5 and 6
    best so far
    anana, length 5

    9Centre 5 meets n against s at once, and centre 6, the s, falls off the end of the word. Both give length 1, so the best does not change.

  10. b0a1n2a3n4a5s6start
    centre
    done
    best so far
    anana, length 5

    10Every centre has been tried. We return the substring from index 1 to index 5, which is anana, the longest palindrome in bananas.

Let us read the important frames back. In frames three and four the first n grows to ana and stops when b meets an a, so ana becomes the best. In frames five to seven the middle a grows through the n pair and the a pair and stops only when b meets s, giving anana.

Notice how the start index is found. We know the centre, 3, and the length, 5. Two of the other four letters sit left of the centre, so the start is 3 - 2 = 1. The code writes this as c - (len - 1) / 2, and the same formula works for an even palindrome, because Java's integer division drops the half.

Across the 13 centres the loop compared letters 22 times, 7 of them a letter with itself, about the same as the brute force on this short word, where most runs fail at once. The difference shows on long, repetitive strings: no pair is ever compared twice from the same centre, so the work is n squared at worst, not n cubed.

6The Java solution, read line by line

Here is the complete program. The method longestPalindrome tries both kinds of centre at every index and keeps the best start and length, and the helper expand does the stepping outward. main runs bananas, noonday, a single letter, a string with no repeated letters and the empty string, and each comment shows what that line prints.

Java
public class LongestPalindrome {
// Expand around each of the 2n - 1 possible centres and keep the longest palindrome seen.
static String longestPalindrome(String s) {
if (s == null || s.isEmpty()) return "";
int bestStart = 0, bestLen = 1;
for (int c = 0; c < s.length(); c++) {
int odd = expand(s, c, c); // centre on one character: "aba"
int even = expand(s, c, c + 1); // centre between two characters: "abba"
int len = Math.max(odd, even);
if (len > bestLen) {
bestLen = len;
bestStart = c - (len - 1) / 2; // works for both odd and even lengths
}
}
return s.substring(bestStart, bestStart + bestLen);
}
// Grows outwards while both ends match; returns the length of the palindrome found.
static int expand(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1; // both ends went one step too far
}
public static void main(String[] args) {
System.out.println(longestPalindrome("bananas")); // anana
System.out.println(longestPalindrome("noonday")); // noon
System.out.println(longestPalindrome("a")); // a
System.out.println(longestPalindrome("abc")); // a
System.out.println("[" + longestPalindrome("") + "]"); // []
}
}

Let us read it in the order it runs. The first line returns an empty string for a null or empty input, because there is no letter to stand on. Then bestStart = 0 and bestLen = 1 record the first letter as the best so far, which is always safe, since any single letter is a palindrome.

The for loop visits each index c once and calls expand twice: expand(s, c, c) puts both fingers on the letter at c, for odd lengths, and expand(s, c, c + 1) puts them on c and the next letter, for even lengths. When c is the last index, c + 1 is beyond the string and expand returns 0.

Inside expand, the while condition checks three things in a careful order: left has not fallen off the start, right has not fallen off the end, and the two letters are equal. The order matters, because Java stops checking as soon as one part is false, so we never call charAt with an index outside the string. When it ends, right - left - 1 is the length strictly between the fingers.

Back in the main loop, len is the larger of the two results. Only when it beats bestLen do we record it, with bestStart = c - (len - 1) / 2. Using a strict greater than means that a tie keeps the earlier palindrome, which is the rule we agreed. The loop keeps two numbers and calls substring only once, at the end.

The tempting mistake in this program is to try only the odd centres. The code would return o for noonday instead of noon, a bug easy to miss on words like bananas whose answers have odd length. Testing one even example, as main does, catches it.

7How much it costs, and the cases at the edges

On bananas the 13 centres tested the loop condition 25 times. In general there are 2n - 1 centres and each can step outward about n divided by 2 times, so the worst case is about n squared steps, O(n squared). The worst case happens on a string like aaaaaaaa, where every centre grows almost to the ends; on ordinary text most centres stop after a step or two.

The space is O(1). However long the string is, the method keeps the same handful of integers, c, left, right, len, bestStart and bestLen, and builds the answer string once at the end. The table version needs n times n true or false values.

Comparing the ways to find the longest palindrome
ApproachTimeExtra space
Test every substring with two fingers (brute force)O(n^3)O(1)
Table isPal[i][j] filled from short runs upO(n^2)O(n^2)
Expand around the 2n - 1 centresO(n^2)O(1)
Manacher's algorithmO(n)O(n)

Now the edge cases, each run by main. An empty string returns from the first line, so main prints []. A single letter starts as the best and comes back unchanged. For abc nothing beats length 1, so the answer stays the first letter, a.

If the whole string is a palindrome, such as racecar, the centre on the e grows to both ends and stops because left falls off the start, which the length formula handles in the same way. If the answer has even length, as in noonday, only the even call can find it.

8Follow-up questions

Is there a way to do this in linear time?

Yes, Manacher's algorithm runs in O(n). It puts a separator between every pair of letters, so every palindrome has odd length. Then it expands around each centre as we did, but it remembers the palindrome reaching furthest right, and a centre inside it starts from the length of its mirror centre instead of from zero, so no letter is compared from scratch more than a constant number of times. In an interview it is enough to know it exists; the centre expansion is the expected answer.

How would you count all the palindromic substrings instead of finding the longest?

The same expansion does it with one change. Every successful step of an expansion is one more palindrome with that centre, so instead of keeping the longest we add one to a counter for every match. For the word aaa the centres find a, a and a from the odd centres, aa and aa from the even centres, and aaa from the middle letter, six in all. It is still O(n squared) time and O(1) space.

What changes if the question asks for the longest palindromic subsequence instead?

A subsequence may skip letters. In the word character the longest palindromic substring is ara, but the longest subsequence is carac, which skips the h. A centre only grows over neighbours, so here we need the table: the best for i to j is 2 plus the best for i + 1 to j - 1 when the end letters match, and otherwise the larger of the best for i + 1 to j and for i to j - 1. That is O(n squared) time and space.

9Conclusion

We found the longest palindrome by trying every possible middle and growing outward while the two ends matched, which removes the repeated work of testing every substring from the outside in. There are 2n - 1 middles, and the method takes O(n squared) time and O(1) space. The clue to remember is the fold: when a range has the property only if the same range with both ends removed has it too, grow each range from its centre instead of listing ranges by start and end.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the details: I return the substring, the first one on a tie, and an empty string gives an empty string. The brute force tries every start and end and tests each run with two pointers, which is O(n cubed), and it repeats work, because testing a long run re-tests the shorter runs inside it.

Then, if they want more

The key fact is that a run is a palindrome when its end characters match and its inside is a palindrome, and all of those runs share one centre. So I will expand around centres. There are 2n - 1 of them: one on each character for odd lengths and one between each pair for even lengths.

For each centre I move left and right outward while both are in range and the characters match. When the loop stops, both have gone one step too far, so the length is right minus left minus 1, and the start is c minus (length minus 1) divided by 2.

I keep the best start and length and build the substring once at the end. That is O(n squared) time in the worst case, for a string of identical letters, and O(1) extra space. I would test noonday, because only the even centre finds noon.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 69 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the longest substring of a string that reads the same forwards and backwards.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-longest-substring-of-a-string-that-reads-the-same-forwa-f18f3a/