VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-common-subsequence-with-no-repeating-character/

⇱ Longest Common Subsequence with no repeating character - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Common Subsequence with no repeating character

Last Updated : 23 Jul, 2025

Given two strings s1 and s2, the task is to find the length of the longest common subsequence with no repeating character.

Examples:

Input: s1= "aabbcc", s2= "aabc"
Output: 3
Explanation: "aabc" is longest common subsequence but it has two repeating character 'a'.
So the required longest common subsequence with no repeating character is "abc".

Input: s1=  "aabcad",  s2= "adbcwcad"
Output: 4
Explanation: The subsequences are "abcd" or "bcad".

Approach: The approach to solve the problem is similar to that of the longest common subsequence using recursion but, also needs to keep track that no two characters are repeated in a subsequence. Follow the steps mentioned below:

  • For each character at the ith position, that character can be part of a sequence or not.
  • Generate every sequence in this way and check for the longest common sequence.
  • To keep track of which characters are included in the subsequence use bits of variable "store".
  • Each bit of variable "store", tells Whether that alphabet is already present or not in a subsequence.
  • bit at 0th position corresponds to character 'a', at position 1 corresponds to 'b', similarly  2 to 'c' so on.

Below is the implementation of the above approach.

 
 


Output
3


 

Time Complexity: O(N * 2N) where N is max(size of s1, size of s2).
Auxiliary Space: O(1)


 

Efficient approach: An efficient approach is to use memoization to reduce the time complexity. Create a 2D dp[][] array where dp[i][j] stores the length of the longest common subsequence with no repeating character till ith index of s1 and jth index of s2 is considered. If characters at s1[i] and s2[j] are same then dp[i][j] = dp[i-1][j-1] + 1, otherwise dp[i][j] = max(dp[i-1][j], dp[i][j-1]). Just keep track of repeating characters as mentioned in the above approach along with this.


 

Note: In the implementation, the dp array is implemented using map where the key is the concatenated string of i and j.


 

Given below is the implementation of the above approach.


 

 
 


Output
3


 

Time Complexity: O(N * M) where N is the size of s1 and M is the size of s2
Auxiliary Space: O(N * M)


 

Comment
Article Tags: