Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Longest palindromic substring

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazonMicrosoftBloomberg

Given a string s, return its longest substring (contiguous) that reads the same forwards and backwards. If several have the maximum length, return the one that starts earliest.

Examples

InputOutputWhy
s = "babad""bab""aba" is as long but starts later.
s = "cbbd""bb"An even-length palindrome.
s = "ac""a"Single characters are palindromes; "a" comes first.

Constraints

  • 1 ≤ s.length ≤ 1000
  • Letters and digits

Hints

Hint 1

Every palindrome is centred on a character (odd length) or between two characters (even length).

Hint 2

From each of the 2n − 1 centres, expand while the characters on both sides match.

Hint 3

Replace the best only when strictly longer, scanning centres from left to right, to keep the earliest on ties.

Where people lose marks

  • Expanding only around characters, which misses even-length palindromes such as "bb".
  • Off-by-one in the final slice after the expansion overshoots by one on each side.
  • Replacing on equal length, which reports the last palindrome instead of the first.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.