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 subsequence

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

Given a string s, return the length of its longest palindromic subsequence: characters taken in order, not necessarily adjacent, that read the same forwards and backwards.

Examples

InputOutputWhy
s = "bbbab"4"bbbb".
s = "cbbd"2"bb".
s = "agbdba"5"abdba".

Constraints

  • 1 ≤ s.length ≤ 1000
  • Lowercase English letters

Hints

Hint 1

Let L[i][j] be the answer for s[i..j]. A single character gives 1.

Hint 2

If s[i] = s[j], both ends can be used: L[i][j] = 2 + L[i + 1][j − 1]. Otherwise drop one end.

Hint 3

Fill by increasing interval length, or loop i downwards and j upwards.

Where people lose marks

  • Confusing it with the longest palindromic substring, which must be contiguous.
  • Filling rows in increasing i, which reads row i + 1 before it exists.
  • Forgetting the case j = i + 1 with equal ends: the inside is empty, worth 0.
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.