VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subsequence-with-different-adjacent-characters/

⇱ Longest subsequence with different adjacent characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest subsequence with different adjacent characters

Last Updated : 12 Jul, 2025

Given string str. The task is to find the longest subsequence of str such that all the characters adjacent to each other in the subsequence are different.

Examples:  

Input: str = "ababa" 
Output:
Explanation: 
"ababa" is the subsequence satisfying the condition

Input: str = "xxxxy" 
Output:
Explanation: 
"xy" is the subsequence satisfying the condition  

Method 1: Greedy Approach 
It can be observed that choosing the first character which is not similar to the previously chosen character given the longest subsequence of the given string with different adjacent characters. 
The idea is to keep track of previously picked characters while iterating through the string, and if the current character is different from the previous character, then count the current character to find the longest subsequence.

Implementation:


Output: 
5

 

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Method 2: Dynamic Programming 

  1. For each character in the given string str, do the following: 
    • Choose the current characters in the string for the resultant subsequence and recur for the remaining string to find the next possible characters for the resultant subsequence.
    • Omit the current characters and recur for the remaining string to find the next possible characters for the resultant subsequence.
  2. The maximum value in the above recursive call will be the longest subsequence with different adjacent elements.
  3. The recurrence relation is given by:
Let dp[pos][prev] be the length of longest subsequence 
till index pos such that alphabet prev was picked previously.a dp[pos][prev] = max(1 + function(pos+1, s[pos] - 'a' + 1, s), 
 function(pos+1, prev, s));

Below is the implementation of the above approach:  


Output: 
5

 

Time Complexity: O(N), where N is the length of the given string. 
Auxiliary Space: O(26*N) where N is the length of the given string.

Approach 2: Using DP Tabulation method ( Iterative approach )

The approach to solving this problem is the same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.

Steps to solve this problem:

  • Create a vector to store the solution of the subproblems.
  • Initialize the table with base cases
  • Fill up the table iteratively
  • Return the final solution

Implementation:


Output
5

Time Complexity: O(N), where N is the length of the given string. 
Auxiliary Space: O(N) where N is the length of the given string.

Comment
Article Tags:
Article Tags: