Given an array of words, print all anagrams together.
For example,
Input: array = {“cat”, “dog”, “tac”, “god”, “act”}
output: cat tac act, dog god
Explanation: cat tac and act are anagrams
and dog and god are anagrams as
they have the same set of characters.
Input: array = {“abc”, “def”, “ghi”}
output: abc, def, ghi
Explanation: There are no anagrams in the array.
Other approaches are discussed herein these posts:
- given-a-sequence-of-words-print-all-anagrams-together
- given-a-sequence-of-words-print-all-anagrams-together-set-2
Approach: This is a HashMap solution using C++ Standard Template Library which stores the Key-Value Pair. In the hashmap, the key will be the sorted set of characters and value will be the output string. Two anagrams will be similar when their characters are sorted. Now,
- Store the vector elements in HashMap with key as the sorted string.
- If the key is same, then add the string to the value of HashMap(string vector).
- Traverse the HashMap and print the anagram strings.
Implementation:
// C++ program for finding all anagram // pairs in the given array #include <algorithm> #include <iostream> #include <unordered_map> #include <vector> using namespace std;
// Utility function for // printing anagram list void printAnagram(unordered_map<string,vector<string> >& store)
{ for ( auto it:store)
{
vector<string> temp_vec(it.second);
int size = temp_vec.size();
for ( int i = 0; i < size; i++)
cout << temp_vec[i] << " " ;
cout << "\n" ;
}
} // Utility function for storing // the vector of strings into HashMap void storeInMap(vector<string>& vec)
{ unordered_map<string,vector<string> > store;
for ( int i = 0; i < vec.size(); i++)
{
string tempString(vec[i]);
// sort the string
sort(tempString.begin(),tempString.end());
// make hash of a sorted string
store[tempString].push_back(vec[i]);
}
// print utility function for printing
// all the anagrams
printAnagram(store);
} // Driver code int main()
{ // initialize vector of strings
vector<string> arr;
arr.push_back( "geeksquiz" );
arr.push_back( "geeksforgeeks" );
arr.push_back( "abcd" );
arr.push_back( "forgeeksgeeks" );
arr.push_back( "zuiqkeegs" );
arr.push_back( "cat" );
arr.push_back( "act" );
arr.push_back( "tca" );
// utility function for storing
// strings into hashmap
storeInMap(arr);
return 0;
} |
import java.util.*;
public class Anagram {
// Utility function for
// printing anagram list
public static void printAnagram(Map<String, List<String>> store) {
for (Map.Entry<String, List<String>> entry : store.entrySet()) {
List<String> tempVec = entry.getValue();
int size = tempVec.size();
for ( int i = 0 ; i < size; i++)
System.out.print(tempVec.get(i) + " " );
System.out.println();
}
}
// Utility function for storing
// the list of strings into HashMap
public static void storeInMap(List<String> arr) {
Map<String, List<String>> store = new HashMap<>();
for ( int i = 0 ; i < arr.size(); i++) {
String tempString = arr.get(i);
// sort the string
char [] tempArr = tempString.toCharArray();
Arrays.sort(tempArr);
tempString = new String(tempArr);
// make hash of a sorted string
if (!store.containsKey(tempString))
store.put(tempString, new ArrayList<>());
store.get(tempString).add(arr.get(i));
}
// print utility function for printing
// all the anagrams
printAnagram(store);
}
// Driver code
public static void main(String[] args) {
// initialize list of strings
List<String> arr = new ArrayList<>();
arr.add( "geeksquiz" );
arr.add( "geeksforgeeks" );
arr.add( "abcd" );
arr.add( "forgeeksgeeks" );
arr.add( "zuiqkeegs" );
arr.add( "cat" );
arr.add( "act" );
arr.add( "tca" );
// utility function for storing
// strings into hashmap
storeInMap(arr);
}
} // this code is added by devendra |
# Python3 program for finding all anagram # pairs in the given array from collections import defaultdict
# Utility function for # printing anagram list def printAnagram(store: dict ) - > None :
for (k, v) in store.items():
temp_vec = v
size = len (temp_vec)
if (size > 1 ):
for i in range (size):
print (temp_vec[i], end = " " )
print ()
# Utility function for storing # the vector of strings into HashMap def storeInMap(vec: list ) - > None :
store = defaultdict( lambda : list )
for i in range ( len (vec)):
tempString = vec[i]
tempString = ''.join( sorted (tempString))
# Check for sorted string
# if it already exists
if (tempString not in store):
temp_vec = []
temp_vec.append(vec[i])
store[tempString] = temp_vec
else :
# Push new string to
# already existing key
temp_vec = store[tempString]
temp_vec.append(vec[i])
store[tempString] = temp_vec
# Print utility function for
# printing all the anagrams
printAnagram(store)
# Driver code if __name__ = = "__main__" :
# Initialize vector of strings
arr = []
arr.append( "geeksquiz" )
arr.append( "geeksforgeeks" )
arr.append( "abcd" )
arr.append( "forgeeksgeeks" )
arr.append( "zuiqkeegs" )
arr.append( "cat" )
arr.append( "act" )
arr.append( "tca" )
# Utility function for storing
# strings into hashmap
storeInMap(arr)
# This code is contributed by sanjeev2552 |
using System;
using System.Collections.Generic;
class Anagram {
// Utility function for
// printing anagram list
public static void
printAnagram(Dictionary< string , List< string > > store)
{
foreach (KeyValuePair< string , List< string > > entry in
store)
{
List< string > tempVec = entry.Value;
int size = tempVec.Count;
for ( int i = 0; i < size; i++)
Console.Write(tempVec[i] + " " );
Console.WriteLine();
}
}
// Utility function for storing
// the list of strings into Dictionary
public static void storeInMap(List< string > arr)
{
Dictionary< string , List< string > > store
= new Dictionary< string , List< string > >();
for ( int i = 0; i < arr.Count; i++) {
string tempString = arr[i];
// sort the string
char [] tempArr = tempString.ToCharArray();
Array.Sort(tempArr);
tempString = new string (tempArr);
// make hash of a sorted string
if (!store.ContainsKey(tempString))
store[tempString] = new List< string >();
store[tempString].Add(arr[i]);
}
// print utility function for printing
// all the anagrams
printAnagram(store);
}
// Driver code
public static void Main( string [] args)
{
// initialize list of strings
List< string > arr = new List< string >();
arr.Add( "geeksquiz" );
arr.Add( "geeksforgeeks" );
arr.Add( "abcd" );
arr.Add( "forgeeksgeeks" );
arr.Add( "zuiqkeegs" );
arr.Add( "cat" );
arr.Add( "act" );
arr.Add( "tca" );
// utility function for storing
// strings into dictionary
storeInMap(arr);
}
} // This code is contributed by prajwal kandekar |
// Utility function for printing anagram list function printAnagram(store) {
for (let entry of Object.entries(store)) {
let tempVec = entry[1];
let size = tempVec.length;
for (let i = 0; i < size; i++)
console.log(tempVec[i]);
console.log( "" );
}
} // Utility function for storing the list of strings into Dictionary function storeInMap(arr) {
let store = {};
for (let i = 0; i < arr.length; i++) {
let tempString = arr[i];
// sort the string
let tempArr = tempString.split( "" );
tempArr.sort();
tempString = tempArr.join( "" );
// make hash of a sorted string
if (!(tempString in store))
store[tempString] = [];
store[tempString].push(arr[i]);
}
// print utility function for printing
// all the anagrams
printAnagram(store);
} // Driver code function main() {
// initialize list of strings
let arr = [];
arr.push( "geeksquiz" );
arr.push( "geeksforgeeks" );
arr.push( "abcd" );
arr.push( "forgeeksgeeks" );
arr.push( "zuiqkeegs" );
arr.push( "cat" );
arr.push( "act" );
arr.push( "tca" );
// utility function for storing
// strings into dictionary
storeInMap(arr);
} main(); //This code is contributed by NarasingaNikhil |
cat act tca abcd geeksforgeeks forgeeksgeeks geeksquiz zuiqkeegs
Note: Compile above program with -std=c++11 flag in g++
Complexity Analysis:
-
Time Complexity: O(n * m(log m)), where m is the length of a word.
A single traversal through the array is needed. -
Space Complexity: O(n).
There are n words in a string. The map requires O(n) space to store the strings.
Another Approach: This program is designed to group anagrams from a given array of strings. The approach taken in this program is as follows:
- Define a function storeInMap that takes a vector of strings as input and creates an unordered_map object to store the anagrams.
- Iterate through each string in the vector and count the frequency of each character in the string.
- Generate a hash string based on the frequency of characters for each string.
- Insert the string into the unordered_map object using the hash string as the key.
- Define another function printAnagram that takes an unordered_map object as input and prints the anagrams.
- Iterate through the unordered_map object and print the anagrams using the values associated with each key.
- In the main function, create a vector of strings containing the input data and call the storeInMap function to group the anagrams.
Implementation:
#include <iostream> #include <unordered_map> #include <vector> using namespace std;
void printAnagram(unordered_map<string, vector<string>>& store) {
for ( auto it : store) {
vector<string> temp_vec(it.second);
int size = temp_vec.size();
for ( int i = 0; i < size; i++)
cout << temp_vec[i] << " " ;
cout << "\n" ;
}
} void storeInMap(vector<string>& vec) {
unordered_map<string, vector<string>> store;
for ( int i = 0; i < vec.size(); i++) {
string tempString(vec[i]);
int charCount[26] = {0};
// count the frequency of each character in the string
for ( char c : tempString) {
charCount++;
}
// generate a hash string based on the frequency of characters
string hashStr = "" ;
for ( int j = 0; j < 26; j++) {
hashStr += to_string(charCount[j]);
hashStr += "#" ;
}
// insert the string into the hashmap
store[hashStr].push_back(vec[i]);
}
// print all the anagrams
printAnagram(store);
} int main() {
vector<string> arr = { "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" };
storeInMap(arr);
return 0;
} // This code is contributed by rudra1807raj |
// Java program to print anagrams together import java.io.*;
import java.util.*;
class GFG {
public static List<List<String>> Anagrams(String[] string_list)
{
HashMap <String, List<String>> mp = new HashMap<>();
List<List<String>> ans = new ArrayList<>();
for (String i: string_list)
{
char ch[] = i.toCharArray();
Arrays.sort(ch);
String s = String.valueOf(ch);
if (mp.containsKey(s))
{
mp.get(s).add(i);
}
else
{
List<String> li = new ArrayList<>();
li.add(i);
mp.put(s,li);
}
}
for (List<String> list: mp.values())
ans.add(list);
return ans;
}
public static void main (String[] args) {
String arr[] = { "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" };
System.out.println(Anagrams(arr));
}
} // This code is contributed by Raunak Singh |
from collections import defaultdict
def print_anagram(store):
for key, value in store.items():
print ( * value)
def store_in_map(arr):
store = defaultdict( list )
for string in arr:
char_count = [ 0 ] * 26
for c in string:
#count the frequency of each character in the string
char_count[ ord (c) - ord ( 'a' )] + = 1
hash_str = '#' .join( map ( str , char_count))
store[hash_str].append(string)
# print all the anagrams
print_anagram(store)
if __name__ = = '__main__' :
arr = [ "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" ]
store_in_map(arr)
#This code is contributed by NarasingaNikhil
|
using System;
using System.Collections.Generic;
class Program
{ static void PrintAnagram(Dictionary< string , List< string >> store)
{ foreach (KeyValuePair< string , List< string >> pair in store)
{ List< string > tempVec = pair.Value;
int size = tempVec.Count;
for ( int i = 0; i < size; i++)
Console.Write(tempVec[i] + " " );
Console.WriteLine();
}
} static void StoreInMap(List< string > vec)
{ Dictionary< string , List< string >> store = new Dictionary< string , List< string >>();
for ( int i = 0; i < vec.Count; i++)
{
string tempString = vec[i];
int [] charCount = new int [26];
// count the frequency of each character in the string
foreach ( char c in tempString)
{
charCount++;
}
// generate a hash string based on the frequency of characters
string hashStr = "" ;
for ( int j = 0; j < 26; j++)
{
hashStr += charCount[j].ToString();
hashStr += "#" ;
}
// insert the string into the hashmap
if (store.ContainsKey(hashStr))
{
store[hashStr].Add(vec[i]);
}
else
{
store[hashStr] = new List< string >();
store[hashStr].Add(vec[i]);
}
}
// print all the anagrams
PrintAnagram(store);
} static void Main()
{ List< string > arr = new List< string > { "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" };
StoreInMap(arr);
} } |
function printAnagram(store) {
for (const [key, value] of Object.entries(store)) {
const tempVec = [...value];
const size = tempVec.length;
for (let i = 0; i < size; i++) {
process.stdout.write(tempVec[i] + " " );
}
console.log();
}
} function storeInMap(arr) {
const store = {};
for (let i = 0; i < arr.length; i++) {
const tempString = arr[i];
const charCount = new Array(26).fill(0);
// Count the frequency of each character in the string
for (const c of tempString) {
charCount++;
}
// Generate a hash string based on the frequency of characters
let hashStr = "" ;
for (let j = 0; j < 26; j++) {
hashStr += charCount[j];
hashStr += "#" ;
}
// Insert the string into the hashmap
if (!store[hashStr]) {
store[hashStr] = [];
}
store[hashStr].push(tempString);
}
// Print all the anagrams
printAnagram(store);
} const arr = [ "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" ,
"zuiqkeegs" , "cat" , "act" , "tca" ];
storeInMap(arr); |
cat act tca abcd geeksforgeeks forgeeksgeeks geeksquiz zuiqkeegs
Time Complexity: The time complexity of this code is O(n*m), where n is the number of strings in the given vector and m is the length of the longest string.
Auxiliary Space: The space complexity of this code is also O(n*m) because we are storing all the strings in the given vector in the store map.
This article is contributed by Mandeep Singh.