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:
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++
#include <algorithm>
#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]);
sort(tempString.begin(),tempString.end());
store[tempString].push_back(vec[i]);
}
printAnagram(store);
}
int main()
{
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" );
storeInMap(arr);
return 0;
}
|
Python3
from collections import defaultdict
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 ()
def storeInMap(vec: list ) - > None :
store = defaultdict( lambda : list )
for i in range ( len (vec)):
tempString = vec[i]
tempString = ''.join( sorted (tempString))
if (tempString not in store):
temp_vec = []
temp_vec.append(vec[i])
store[tempString] = temp_vec
else :
temp_vec = store[tempString]
temp_vec.append(vec[i])
store[tempString] = temp_vec
printAnagram(store)
if __name__ = = "__main__" :
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" )
storeInMap(arr)
|
Java
import java.util.*;
public class Anagram {
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();
}
}
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);
char [] tempArr = tempString.toCharArray();
Arrays.sort(tempArr);
tempString = new String(tempArr);
if (!store.containsKey(tempString))
store.put(tempString, new ArrayList<>());
store.get(tempString).add(arr.get(i));
}
printAnagram(store);
}
public static void main(String[] args) {
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" );
storeInMap(arr);
}
}
|
C#
using System;
using System.Collections.Generic;
class Anagram {
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();
}
}
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];
char [] tempArr = tempString.ToCharArray();
Array.Sort(tempArr);
tempString = new string (tempArr);
if (!store.ContainsKey(tempString))
store[tempString] = new List< string >();
store[tempString].Add(arr[i]);
}
printAnagram(store);
}
public static void Main( string [] args)
{
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" );
storeInMap(arr);
}
}
|
Javascript
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( "" );
}
}
function storeInMap(arr) {
let store = {};
for (let i = 0; i < arr.length; i++) {
let tempString = arr[i];
let tempArr = tempString.split( "" );
tempArr.sort();
tempString = tempArr.join( "" );
if (!(tempString in store))
store[tempString] = [];
store[tempString].push(arr[i]);
}
printAnagram(store);
}
function main() {
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" );
storeInMap(arr);
}
main();
|
Outputcat 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:
C++
#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};
for ( char c : tempString) {
charCount++;
}
string hashStr = "" ;
for ( int j = 0; j < 26; j++) {
hashStr += to_string(charCount[j]);
hashStr += "#" ;
}
store[hashStr].push_back(vec[i]);
}
printAnagram(store);
}
int main() {
vector<string> arr = { "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" };
storeInMap(arr);
return 0;
}
|
Java
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));
}
}
|
Python3
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:
char_count[ ord (c) - ord ( 'a' )] + = 1
hash_str = '#' .join( map ( str , char_count))
store[hash_str].append(string)
print_anagram(store)
if __name__ = = '__main__' :
arr = [ "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" ]
store_in_map(arr)
|
C#
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];
foreach ( char c in tempString)
{
charCount++;
}
string hashStr = "" ;
for ( int j = 0; j < 26; j++)
{
hashStr += charCount[j].ToString();
hashStr += "#" ;
}
if (store.ContainsKey(hashStr))
{
store[hashStr].Add(vec[i]);
}
else
{
store[hashStr] = new List< string >();
store[hashStr].Add(vec[i]);
}
}
PrintAnagram(store);
}
static void Main()
{
List< string > arr = new List< string > { "geeksquiz" , "geeksforgeeks" , "abcd" , "forgeeksgeeks" , "zuiqkeegs" , "cat" , "act" , "tca" };
StoreInMap(arr);
}
}
|
Outputcat 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. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.