Longest Palindromic Subsequence
Updated
Problem statement
Find the longest subsequence of the string s that is a palindrome, and return how many characters it has.
A subsequence is what remains after deleting zero or more characters from s; the remaining characters keep their original order but do not have to be next to each other. A palindrome is a string that is the same when it is reversed.
Function
longestPalindromeSubseq(s: String) → intExamples
Example 1
s = "kabcbdk"return = 5The letters k, b, c, b, k (positions 0, 2, 3, 4 and 6) form kbcbk, which reads the same both ways, so the answer is at least 5. It cannot be longer: in a palindrome every letter except possibly the middle one is matched by the same letter on the other side, so only one letter may be used an odd number of times. Here k and b appear twice each and a, c and d once each, so at most 2 + 2 + 1 = 5 letters can be used.
Example 2
s = "abab"return = 3aba (positions 0, 1 and 2) is a palindrome of length 3. The only subsequence of length 4 is the whole string abab, which reads baba backwards, so it is not a palindrome. The answer is 3, even though each letter appears twice.
Example 3
s = "abcd"return = 1No letter appears twice. A palindrome of length 2 or more needs its first and last letters to be equal, taken from two different positions, so none exists here. A single letter is a palindrome, so the answer is 1.
Constraints
1 <= s.length <= 1000sconsists only of lowercase English letters.
More AXQ Capital Online Assessment questions
Similar questions at other companies
- Maximum Equal-Bit Pairs in a SubsequenceAmazon · OA
- Longest Subsequence That Is a SubstringBooking.com · OA
- Count Digit Replacements with No Equal Adjacent DigitsMicrosoft · OAMicrosoft interview questions
- Palindrome CounterGoldman Sachs · OAGoldman Sachs interview questions
- Longest String ChainVisa · OAVisa interview questions
- Minimum-Cost Digit String DecodingSquadStack.ai · OA
- Maximum Redundancy After One Segment FlipBloomberg LP · OABloomberg LP interview questions
- Substrings Without a Target SubsequencePhonePe · OAPhonePe interview questions
- Minimum Edit-Distance String for Each QueryTarget · OA
- Longest Subsequence That Is a SubstringWells Fargo · OAWells Fargo interview questions