VOOZH about

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

⇱ Longest common anagram subsequence from N strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest common anagram subsequence from N strings

Last Updated : 11 Jul, 2025

Given N strings. Find the longest possible subsequence from each of these N strings such that they are anagram to each other. The task is to print the lexicographically largest subsequence among all the subsequences. 

Examples:

Input: s[] = { geeks, esrka, efrsk } 
Output: ske 
First string has "eks", Second string has "esk", third string has "esk". These three are anagrams. "ske" is lexicographically large. 

Input: string s[] = { loop, lol, olive } 
Output: ol

Approach : 

  • Make a 2-D array of n*26 to store the frequency of each character in string.
  • After making frequency array, traverse in reverse direction for each digit and find the string which has the minimum characters of this type.
  • After complete reverse traversal, print the character that occurs the minimum number of times since it gives the lexicographically largest string.

Below is the implementation of the above approach.  


Output
ol

Complexity Analysis:

  • Time Complexity: O(n2)
  • Auxiliary space: O(1). 

Please suggest if someone has a better solution which is more efficient in terms of space and time.

Approach#2: Using counter

This approach finds the longest common anagram subsequence from a given list of strings by first counting the frequency of characters in each string using the Counter function from the collections module. It then finds the intersection of all the character frequency dictionaries to obtain the common characters, and finally returns the sorted string of common characters.

Algorithm

1. Create a list of character frequency dictionaries for each string using Counter function
2. Find the intersection of all frequency dictionaries using bitwise & operator
3. Obtain the common characters by concatenating the elements of the intersection frequency dictionary
4. Return the sorted common characters as the longest common anagram subsequence


Output
eks
lo

Time Complexity: O(mnlogn), where m is the length of the longest string and n is the number of strings. The time complexity is dominated by the sorting operation at the end of the function.

Space Complexity: O(mn), where m is the length of the longest string and n is the number of strings. The space complexity is dominated by the list of character frequency dictionaries.

Comment