Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to find the length of the longest subsequence which is present in both the strings in the form of anagrams.
Note: The strings contain only lowercase letters.
Input : str1 = "abdacp", str2 = "ckamb" Output : 3 Subsequence of str1 = abc Subsequence of str2 = cab OR Subsequence of str1 = bac Subsequence of str2 = cab These are longest common anagram subsequences. Input : str1 = "abbcfke", str2 = "fbaafbly" Output : 4
Approach: Create two hash tables say freq1 and freq2. Store frequencies of each character of str1 in freq1. Likewise, store frequencies of each character of str2 in freq2. Initilaize len = 0. Now, for each lowercase letter finds its lowest frequency from the two hash tables and accumulate it to len.
Length = 3
Time Complexity: O(n).
Auxiliary Space: O(n).
- Longest common anagram subsequence from N strings
- Longest Common Subsequence | DP-4
- LCS (Longest Common Subsequence) of three strings
- Longest Common Subsequence | DP using Memoization
- Printing Longest Common Subsequence
- Longest Common Increasing Subsequence (LCS + LIS)
- Edit distance and LCS (Longest Common Subsequence)
- Length of longest common subsequence containing vowels
- Longest Subsequence with at least one common digit in every element
- Longest common subsequence with permutations allowed
- Longest subsequence such that adjacent elements have at least one common digit
- Printing Longest Common Subsequence | Set 2 (Printing All)
- Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime
- Count common subsequence in two strings
- Longest subsequence with a given AND value | O(N)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.