Longest palindromic subsequence

Dynamic Programming DP on strings Hard
  • This problem's underlying concept is usually used in data analysis, natural language processing, and data validation
  • For instance, in DNA or RNA sequence analysis, to ensure the palindromic sequences (which are vital for some biological functions), the concept of minimum insertions to make a palindrome is applied
  • In Natural Language Processing, text-based user interfaces and chatbots might use it to generate 'palindromic sentences', which could be a fun feature or a useful tool for linguistic studies
  • Also, it teaches us about dynamic programming, a Method used throughout programming for optimizing problems by breaking them down into simpler subproblems

Given a string, Find the longest palindromic subsequence length in given string.


A palindrome is a sequence that reads the same backwards as forward.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Examples:

Input: s = "eeeme"

Output: 4

Explanation: The longest palindromic subsequence is "eeee", which has a length of 4.

Input: s = "annb"

Output: 2

Explanation: The longest palindromic subsequence is "nn", which has a length of 2.

Input: s = "s"

Constraints

  • 1 ≤ s.length ≤ 1000

Hints

  • "Define dp[i][j] as the length of the longest palindromic subsequence in s[i:j]. Recurrence Relation: If s[i] == s[j]: dp[i][j]=dp[i+1][j−1]+2 Otherwise, remove one character and take the maximum LPS found: dp[i][j]=max(dp[i+1][j],dp[i][j−1])"

Company Tags

Bungie Mastercard Rakuten Wayfair Johnson & Johnson Siemens Healthineers Morgan Stanley Roche Dropbox AMD DoorDash Unity Technologies McKinsey & Company Target Boston Consulting Group Pinterest American Express OYO Rooms Square Etsy Activision Blizzard Cerner ARM Salesforce IBM Google Microsoft Amazon Meta Apple Netflix Adobe