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+m).
Auxiliary Space: O(1).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Longest common anagram subsequence from N strings
- Longest Common Subsequence | DP-4
- Longest Common Subsequence | DP using Memoization
- LCS (Longest Common Subsequence) of three strings
- Longest Common Increasing Subsequence (LCS + LIS)
- Printing Longest Common Subsequence
- Longest common subsequence with permutations allowed
- Longest Subsequence with at least one common digit in every element
- Length of longest common subsequence containing vowels
- Edit distance and LCS (Longest Common Subsequence)
- 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 Common Substring | DP-29
- Longest Common Prefix using Sorting
- Longest Common Prefix Matching | Set-6
- Longest Common Extension / LCE | Set 2 ( Reduction to RMQ)
- Print the longest common substring
- Longest Common Prefix using Trie
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.