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[] = { neveropen, 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.
C++14
// C++ program to find longest possible // subsequence anagram of N strings. #include <bits/stdc++.h> using namespace std; const int MAX_CHAR = 26; // function to store frequency of // each character in each string void frequency( int fre[][MAX_CHAR], string s[], int n) { for ( int i = 0; i < n; i++) { string str = s[i]; for ( int j = 0; j < str.size(); j++) fre[i][str[j] - 'a' ]++; } } // function to Find longest possible sequence of N // strings which is anagram to each other void LongestSequence( int fre[][MAX_CHAR], int n) { // to get lexicographical largest sequence. for ( int i = MAX_CHAR-1; i >= 0; i--) { // find minimum of that character int mi = fre[0][i]; for ( int j = 1; j < n; j++) mi = min(fre[j][i], mi); // print that character // minimum number of times while (mi--) cout << ( char )( 'a' + i); } } // Driver code int main() { string s[] = { "loo" , "lol" , "olive" }; int n = sizeof (s)/ sizeof (s[0]); // to store frequency of each character in each string int fre[n][26] = { 0 }; // to get frequency of each character frequency(fre, s, n); // function call LongestSequence(fre, n); return 0; } |
Java
// Java program to find longest // possible subsequence anagram // of N strings. class GFG { final int MAX_CHAR = 26 ; // function to store frequency // of each character in each // string static void frequency( int fre[][], String s[], int n) { for ( int i = 0 ; i < n; i++) { String str = s[i]; for ( int j = 0 ; j < str.length(); j++) fre[i][str.charAt(j) - 'a' ]++; } } // function to Find longest // possible sequence of N // strings which is anagram // to each other static void LongestSequence( int fre[][], int n) { // to get lexicographical // largest sequence. for ( int i = 25 ; i >= 0 ; i--) { // find minimum of // that character int mi = fre[ 0 ][i]; for ( int j = 1 ; j < n; j++) mi = Math.min(fre[j][i], mi); // print that character // minimum number of times while (mi--!= 0 ) System.out.print(( char )( 'a' + i)); } } // Driver code public static void main(String args[]) { String s[] = { "loo" , "lol" , "olive" }; int n = s.length; // to store frequency of each // character in each string int fre[][] = new int [n][ 26 ] ; // to get frequency // of each character frequency(fre, s, n); // function call LongestSequence(fre, n); } } // This code is contributed // by Arnab Kundu |
Python3
# Python3 program to find longest possible # subsequence anagram of N strings. # Function to store frequency of # each character in each string def frequency(fre, s, n): for i in range ( 0 , n): string = s[i] for j in range ( 0 , len (string)): fre[i][ ord (string[j]) - ord ( 'a' )] + = 1 # Function to Find longest possible sequence # of N strings which is anagram to each other def LongestSequence(fre, n): # to get lexicographical largest sequence. for i in range (MAX_CHAR - 1 , - 1 , - 1 ): # find minimum of that character mi = fre[ 0 ][i] for j in range ( 1 , n): mi = min (fre[j][i], mi) # print that character # minimum number of times while mi: print ( chr ( ord ( 'a' ) + i), end = "") mi - = 1 # Driver code if __name__ = = "__main__" : s = [ "loo" , "lol" , "olive" ] n = len (s) MAX_CHAR = 26 # to store frequency of each # character in each string fre = [[ 0 for i in range ( 26 )] for j in range (n)] # To get frequency of each character frequency(fre, s, n) # Function call LongestSequence(fre, n) # This code is contributed by # Rituraj Jain |
C#
// c# program to find longest // possible subsequence anagram // of N strings. using System; class GFG { public readonly int MAX_CHAR = 26; // function to store frequency // of each character in each // string public static void frequency( int [,] fre, string [] s, int n) { for ( int i = 0; i < n; i++) { string str = s[i]; for ( int j = 0; j < str.Length; j++) { fre[i, str[j] - 'a' ]++; } } } // function to Find longest // possible sequence of N // strings which is anagram // to each other public static void LongestSequence( int [, ] fre, int n) { // to get lexicographical // largest sequence. for ( int i = 24; i >= 0; i--) { // find minimum of // that character int mi = fre[0, i]; for ( int j = 1; j < n; j++) { mi = Math.Min(fre[j, i], mi); } // print that character // minimum number of times while (mi--!=0) { Console.Write(( char )( 'a' + i)); } } } // Driver code public static void Main( string [] args) { string [] s = new string [] { "loo" , "lol" , "olive" }; int n = s.Length; // to store frequency of each // character in each string int [, ] fre = new int [n, 26]; // to get frequency // of each character frequency(fre, s, n); // function call LongestSequence(fre, n); } } // This code is contributed by Shrikanth13 |
Javascript
<script> // JavaScript program to find longest // possible subsequence anagram // of N strings. let MAX_CHAR = 26; // function to store frequency // of each character in each // string function frequency(fre,s,n) { for (let i = 0; i < n; i++) { let str = s[i]; for (let j = 0; j < str.length; j++) fre[i][str[j].charCodeAt(0) - 'a' .charCodeAt(0)]++; } } // function to Find longest // possible sequence of N // strings which is anagram // to each other function LongestSequence(fre,n) { // to get lexicographical // largest sequence. for (let i = 24; i >= 0; i--) { // find minimum of // that character let mi = fre[0][i]; for (let j = 1; j < n; j++) mi = Math.min(fre[j][i], mi); // print that character // minimum number of times while (mi--!=0) document.write(String.fromCharCode ( 'a' .charCodeAt(0) + i)); } } // Driver code let s=[ "loo" , "lol" , "olive" ]; let n = s.length; // to store frequency of each // character in each string let fre = new Array(n) ; for (let i=0;i<n;i++) { fre[i]= new Array(26); for (let j=0;j<26;j++) fre[i][j]=0; } // to get frequency // of each character frequency(fre, s, n); // function call LongestSequence(fre, n); // This code is contributed by avanitrachhadiya2155 </script> |
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.
This article is contributed by Aarti_Rathi.
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
Python3
from collections import Counter def longest_common_anagram_subsequence(strings): # Count character frequencies in each string and find the intersection of all dictionaries freq_dicts = [Counter(string) for string in strings] common_freq = freq_dicts[ 0 ] for freq_dict in freq_dicts[ 1 :]: common_freq & = freq_dict # Find the longest anagram subsequence using the common character frequencies common_chars = ''.join(common_freq.elements()) return ''.join( sorted (common_chars)) # Example usage strings = [ "neveropen" , "esrka" , "efrsk" ] print (longest_common_anagram_subsequence(strings)) strings = [ "loop" , "lol" , "olive" ] print (longest_common_anagram_subsequence(strings)) |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!