Longest palindromic substring

A free hard coding practice problem. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Hard
Type
Function
Languages
JavaScript, TypeScript or Python

Problem

Return the longest substring of s that is a palindrome. If several have the same length, return the leftmost. Strings can be 2,000 characters long.

Function signature

// JavaScript
function longestPalindrome(s)

// TypeScript
function longestPalindrome(s: any): any

// Python
def longest_palindrome(s):

Examples

  1. longestPalindrome("babad") → "bab"
  2. longestPalindrome("cbbd") → "bb"
  3. longestPalindrome("a") → "a"

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps