VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-common-anagram-subsequence/

⇱ Longest Common Anagram Subsequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Common Anagram Subsequence

Last Updated : 27 Sep, 2022

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.

Examples: 

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. Initialize len = 0. Now, for each lowercase letter finds its lowest frequency from the two hash tables and accumulate it to len.

Implementation:


Output
Length = 3

Time Complexity: O(n+m). 
Auxiliary Space: O(1).

Comment