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.
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>
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
C++
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
string longestCommonAnagramSubsequence(vector<string>& strings) {
// Count character frequencies in each string and find the intersection of all maps
unordered_map<char, int> commonFreq;
unordered_map<char, int> freqMap;
for (const string& str : strings) {
freqMap.clear();
for (char c : str) {
freqMap[c] = freqMap[c] + 1;
}
if (commonFreq.empty()) {
commonFreq = freqMap;
} else {
for (auto& entry : commonFreq) {
char key = entry.first;
int commonCount = min(entry.second, freqMap[key]);
entry.second = commonCount;
}
}
}
// Find the longest anagram subsequence using the common character frequencies
string commonChars;
for (const auto& entry : commonFreq) {
char key = entry.first;
int count = entry.second;
commonChars.append(count, key);
}
sort(commonChars.begin(), commonChars.end());
return commonChars;
}
int main() {
vector<string> strings1 = {"geeks", "esrka", "efrsk"};
cout << longestCommonAnagramSubsequence(strings1) << endl;
vector<string> strings2 = {"loop", "lol", "olive"};
cout << longestCommonAnagramSubsequence(strings2) << endl;
return 0;
}
// This code is contributed by akshitaguprzj3
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static String longestCommonAnagramSubsequence(String[] strings) {
// Count character frequencies in each string and find the intersection of all maps
Map<Character, Integer> commonFreq = new HashMap<>();
Map<Character, Integer> freqMap;
for (String str : strings) {
freqMap = new HashMap<>();
for (char c : str.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
if (commonFreq.isEmpty()) {
commonFreq.putAll(freqMap);
} else {
for (Map.Entry<Character, Integer> entry : commonFreq.entrySet()) {
char key = entry.getKey();
int commonCount = Math.min(entry.getValue(), freqMap.getOrDefault(key, 0));
entry.setValue(commonCount);
}
}
}
// Find the longest anagram subsequence using the common character frequencies
StringBuilder commonChars = new StringBuilder();
for (Map.Entry<Character, Integer> entry : commonFreq.entrySet()) {
char key = entry.getKey();
int count = entry.getValue();
for (int i = 0; i < count; i++) {
commonChars.append(key);
}
}
char[] commonCharsArray = commonChars.toString().toCharArray();
java.util.Arrays.sort(commonCharsArray);
return new String(commonCharsArray);
}
public static void main(String[] args) {
String[] strings1 = {"geeks", "esrka", "efrsk"};
System.out.println(longestCommonAnagramSubsequence(strings1));
String[] strings2 = {"loop", "lol", "olive"};
System.out.println(longestCommonAnagramSubsequence(strings2));
}
}
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 = ["geeks", "esrka", "efrsk"]
print(longest_common_anagram_subsequence(strings))
strings = ["loop", "lol", "olive"]
print(longest_common_anagram_subsequence(strings))
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string LongestCommonAnagramSubsequence(List<string> strings)
{
// Count character frequencies in each string and find the intersection of all maps
Dictionary<char, int> commonFreq = new Dictionary<char, int>();
Dictionary<char, int> freqMap = new Dictionary<char, int>();
foreach (var str in strings)
{
freqMap.Clear();
foreach (char c in str)
{
if (freqMap.ContainsKey(c))
freqMap[c]++;
else
freqMap[c] = 1;
}
if (commonFreq.Count == 0)
{
commonFreq = new Dictionary<char, int>(freqMap);
}
else
{
foreach (var entry in commonFreq.ToList())
{
char key = entry.Key;
int commonCount = Math.Min(entry.Value, freqMap.ContainsKey(key) ? freqMap[key] : 0);
commonFreq[key] = commonCount;
}
}
}
// Find the longest anagram subsequence using the common character frequencies
string commonChars = new string(commonFreq.SelectMany(entry => Enumerable.Repeat(entry.Key, entry.Value)).ToArray());
char[] charArray = commonChars.ToCharArray();
Array.Sort(charArray);
return new string(charArray);
}
static void Main()
{
List<string> strings1 = new List<string> { "geeks", "esrka", "efrsk" };
Console.WriteLine(LongestCommonAnagramSubsequence(strings1));
List<string> strings2 = new List<string> { "loop", "lol", "olive" };
Console.WriteLine(LongestCommonAnagramSubsequence(strings2));
}
}
// this code is contributed by utkarsh
JavaScript
function longestCommonAnagramSubsequence(strings) {
// Count character frequencies in each string and find the intersection of all maps
let commonFreq = new Map();
let freqMap = new Map();
for (const str of strings) {
freqMap.clear();
for (const c of str) {
freqMap.set(c, (freqMap.get(c) || 0) + 1);
}
if (commonFreq.size === 0) {
commonFreq = new Map(freqMap);
} else {
for (const [key, value] of commonFreq.entries()) {
const commonCount = Math.min(value, freqMap.get(key) || 0);
commonFreq.set(key, commonCount);
}
}
}
// Find the longest anagram subsequence using the common character frequencies
let commonChars = '';
for (const [key, count] of commonFreq.entries()) {
commonChars += key.repeat(count);
}
commonChars = commonChars.split('').sort().join('');
return commonChars;
}
// Main function
function main() {
const strings1 = ["geeks", "esrka", "efrsk"];
console.log(longestCommonAnagramSubsequence(strings1));
const strings2 = ["loop", "lol", "olive"];
console.log(longestCommonAnagramSubsequence(strings2));
}
// Run the main function
main();
// This code is contributed by shivamgupta310570
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem