![]() |
VOOZH | about |
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 :
Below is the implementation of the above approach.
ol
Complexity Analysis:
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.
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
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.