Longest palindromic substring in JavaScript
Advanced · 3 min read
A palindrome reads the same forwards and backwards, like 'level' or 'racecar'. Hidden inside 'bananas' is a five-letter one: 'anana'. Finding the longest palindrome inside a string is a popular interview question, and the method you will use, "expand around the center", is short, fast and easy to picture.
In this tutorial you will write longestPalindrome(text). You will learn why a string of length n has 2n - 1 centers, fix the off-by-one that trips most people up, and decide what to do when two answers tie. You need to know loops, strings and functions.
Checking a palindrome
To test a whole string, reverse it and compare. [...s] splits it into characters, reverse() flips them and join('') glues them back:
const isPal = (s) => s === [...s].reverse().join('');
console.log(isPal('anana')); // true
console.log(isPal('banana')); // false
Every palindrome has a center
Read a palindrome from its middle outwards, and the two sides match step by step. In 'racecar' the middle is the e. In 'abba' the middle is the gap between the two bs.
So odd-length palindromes are centered on a character, and even-length ones are centered on a gap between two characters. A string of n characters has n characters and n - 1 gaps, which makes 2n - 1 possible centers. For a five-character string, that is 9.
Here is the exercise. Try it on your own first if you like, or read on and we will build it step by step.
27 Longest palindromic substring
hardFind the longest palindrome inside a string. 'bananas' gives 'anana'. 'abracadabra' has two three-letter answers, so ties must be decided.
Stuck? Three hints, smallest first
- 1. Expand around each centre. There are
2n-1centres, notn. - 2. Even-length palindromes have their centre between two characters.
- 3. The answer is not unique; pick the first and say so.
Step 1: expand from a center
Start with a left and right position. While both are inside the string and their characters match, step them one place outwards:
const text = 'bananas';
function expand(left, right) {
while (left >= 0 && right < text.length && text[left] === text[right]) {
left--;
right++;
}
return text.slice(left + 1, right);
}
console.log(expand(3, 3)); // 'anana': centered on the middle 'a'
console.log(expand(0, 0)); // 'b'
Step 2: the off-by-one
Why slice(left + 1, right)? The loop stops when the characters stop matching, or when an edge runs off the string. By then left and right have each gone one step too far.
For expand(3, 3) on 'bananas', the loop ends with left at 0 (the b) and right at 6 (the s). Neither belongs in the answer. slice(1, 6) gives the characters at positions 1 to 5, which is 'anana'. Remember that slice already leaves out its end position, so right needs no adjustment.
Step 3: try every character as a center
Loop over each position and keep the longest result:
function oddOnly(text) {
const expand = (left, right) => {
while (left >= 0 && right < text.length && text[left] === text[right]) { left--; right++; }
return text.slice(left + 1, right);
};
let best = text.slice(0, 1);
for (let i = 0; i < text.length; i++) {
const odd = expand(i, i);
if (odd.length > best.length) best = odd;
}
return best;
}
console.log(oddOnly('bananas')); // 'anana'
console.log(oddOnly('cbbd')); // 'c', but 'bb' is longer
This works for 'bananas', but it misses 'bb' in 'cbbd'. Only n centers were checked, so every even-length palindrome is invisible.
Step 4: add the gaps
For the gap after position i, start with left = i and right = i + 1. Check both kinds of center at every position:
function longestPalindrome(text) {
if (text.length < 2) return text;
let best = text.slice(0, 1);
const expand = (left, right) => {
while (left >= 0 && right < text.length && text[left] === text[right]) { left--; right++; }
return text.slice(left + 1, right);
};
for (let i = 0; i < text.length; i++) {
const odd = expand(i, i);
const even = expand(i, i + 1);
for (const candidate of [odd, even]) {
if (candidate.length > best.length) best = candidate;
}
}
return best;
}
console.log(longestPalindrome('cbbd')); // 'bb'
console.log(longestPalindrome('abba')); // 'abba'
console.log(longestPalindrome('forgeeksskeegfor')); // 'geeksskeeg'
console.log(longestPalindrome('')); // ''
A string shorter than two characters is its own answer, so the function returns it straight away. If no two characters match, the best is a single letter: longestPalindrome('abc') gives 'a'.
Step 5: decide what happens with ties
'abracadabra' contains two three-letter palindromes, 'aca' and 'ada'. Which one should come back?
console.log(longestPalindrome('abracadabra')); // 'aca'
console.log(longestPalindrome('babad')); // 'bab'
The check is >, "strictly longer". A later palindrome of the same length doesn't replace the current best, so the first one found wins. That is a choice, so write it down. The full answer also has allLongestPalindromes, which returns every palindrome of the best length, so you can see both.
The full solution
The panel has longestPalindrome, allLongestPalindromes and the isPal check. It prints the answer for nine strings, both three-letter answers in 'abracadabra', and the number of centers for a five-character string. Press Run to see the output.
/* Expand around centres. A string of length n has 2n-1 centres: n single
characters, and n-1 gaps between them for even-length palindromes. */
function longestPalindrome(text) {
if (text.length < 2) return text;
let best = text.slice(0, 1);
const expand = (left, right) => {
while (left >= 0 && right < text.length && text[left] === text[right]) { left--; right++; }
return text.slice(left + 1, right); // one step too far, so step back
};
for (let i = 0; i < text.length; i++) {
const odd = expand(i, i); // centred on a character
const even = expand(i, i + 1); // centred between two
for (const candidate of [odd, even]) {
if (candidate.length > best.length) best = candidate; // > , so the FIRST tie wins
}
}
return best;
}
// Every maximal palindrome, since the question wants them all.
function allLongestPalindromes(text) {
const best = longestPalindrome(text).length;
const found = new Set();
for (let i = 0; i < text.length; i++) {
for (let j = i + best; j <= text.length; j++) {
const piece = text.slice(i, j);
if (piece.length === best && piece === [...piece].reverse().join('')) found.add(piece);
}
}
return [...found];
}
const isPal = (s) => s === [...s].reverse().join('');
for (const t of ['bananas', 'abracadabra', 'babad', 'cbbd', 'a', '', 'abc', 'aaaa', 'forgeeksskeegfor']) {
console.log(JSON.stringify(t).padEnd(19), '->', JSON.stringify(longestPalindrome(t)));
}
console.log("all three-letter answers in 'abracadabra':", allLongestPalindromes('abracadabra'));
console.log('centres for a 5-character string:', 2 * 5 - 1);
Output
17 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 17 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the example in the question: bananas gives anana", longestPalindrome('bananas'), 'anana');
test('an even-length palindrome is found', longestPalindrome('cbbd'), 'bb');
test('which needs the between-characters centres', longestPalindrome('abba'), 'abba');
test("'babad' gives the first of two", longestPalindrome('babad'), 'bab');
test("'abracadabra' gives aca, the first three-letter one", longestPalindrome('abracadabra'), 'aca');
test('and both candidates are found', allLongestPalindromes('abracadabra').sort(), ['aca', 'ada']);
test('a single character', longestPalindrome('a'), 'a');
test('an empty string', longestPalindrome(''), '');
test('no palindrome longer than one character', longestPalindrome('abc'), 'a');
test('all the same character is one palindrome', longestPalindrome('aaaa'), 'aaaa');
test('a long one inside a longer string', longestPalindrome('forgeeksskeegfor'), 'geeksskeeg');
test('the result really is a palindrome', isPal(longestPalindrome('bananas')), true);
test('and that holds for every case', ['bananas', 'abracadabra', 'babad', 'cbbd', 'a', 'abc', 'aaaa'].every((t) => isPal(longestPalindrome(t))), true);
test('the result is a contiguous slice', ['bananas', 'abracadabra', 'forgeeksskeegfor'].every((t) => t.includes(longestPalindrome(t))), true);
test('there are 2n-1 centres to check', 2 * 5 - 1, 9);
test('an odd-length answer comes from a character centre', longestPalindrome('aba').length % 2, 1);
test('and an even-length one from a gap', longestPalindrome('abba').length % 2, 0);
The count of centres is the thing to get right: 2n−1, not n. Every single character is a centre for odd-length palindromes, and every gap between two characters is a centre for even-length ones. Check only the characters and you never find 'bb' or 'abba' — both are asserted for that reason.
expand stops when the characters stop matching, by which point left and right have each gone one step too far, hence slice(left + 1, right). That off-by-one is the usual bug in this function.
The answer is not unique: 'abracadabra' contains both 'aca' and 'ada'. > rather than >= in the comparison makes the first win, and allLongestPalindromes returns both so the choice is visible rather than accidental.
Common mistakes
- Checking only n centers. Even-length palindromes sit on gaps between characters. Without those,
'abba'and'bb'are never found. - Slicing with
slice(left, right + 1). When the loop stops, both edges are one step past the palindrome. Useslice(left + 1, right). - Not deciding the tie rule.
>keeps the first answer,>=keeps the last. Pick one on purpose.
Try it yourself
- Return the length of the longest palindrome instead of the text. For
'bananas'that is 5. - Change the tie rule so the last palindrome of the best length wins, and check
'abracadabra'gives'ada'. - Make a version that ignores case, so
'Abba'gives'Abba'.