VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-palindromic-subsequence-of-two-distinct-characters/

⇱ Longest Palindromic Subsequence of two distinct characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Palindromic Subsequence of two distinct characters

Last Updated : 15 Jul, 2025

Given a string S of lowercase letters, the task is to find the length of the longest palindromic subsequence made up of two distinct characters only.
 

Examples: 

Input: S = "bbccdcbb" 
Output:
Explanation: 
The longest palindromic subsequence of the desired form is "bbcccbb", which is of length 7.
Input: S = "aeea" 
Output:
Explanation: 
The longest palindromic subsequence of desired form is "aeea", which is of length 4. 

Approach: 
In order to solve the problem, we need to follow the steps below:  

Below is the implementation of the above approach:
 


Output: 
7

 

Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(N), for creating 26 arrays of size N, the space complexity will be O(26*N) which is equivalent to O(N).

Comment