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.
C++
// 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 listvoid printAnagram( unordered_map<string, vector<string> >& store){ unordered_map<string, vector<string> >::iterator it; for (it = store.begin(); it != store.end(); it++) { vector<string> temp_vec(it->second); int size = temp_vec.size(); if (size > 1) { for (int i = 0; i < size; i++) { cout << temp_vec[i] << " "; } cout << "\n"; } }}// Utility function for storing// the vector of strings into HashMapvoid 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()); // Check for sorted string // if it already exists if (store.find( tempString) == store.end()) { vector<string> temp_vec; temp_vec.push_back(vec[i]); store.insert(make_pair( tempString, temp_vec)); } else { // Push new string to // already existing key vector<string> temp_vec( store[tempString]); temp_vec.push_back(vec[i]); store[tempString] = temp_vec; } } // print utility function for printing // all the anagrams printAnagram(store);}// Driver codeint 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;} |
Python3
# Python3 program for finding all anagram# pairs in the given arrayfrom collections import defaultdict# Utility function for# printing anagram listdef 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 HashMapdef 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 codeif __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 |
Note: Compile above program with -std=c++11 flag in g++
Output:
cat act tca geeksforgeeks forgeeksgeeks geeksquiz zuiqkeegs
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.
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Given a sequence of words, print all anagrams together | Set 2
- Given a sequence of words, print all anagrams together | Set 1
- Print anagrams together in Python using List and Dictionary
- Print all pairs of anagrams in a given array of strings
- Find and print duplicate words in std::vector<string> using STL functions
- Check if the given string of words can be formed from words present in the dictionary
- Largest number from the longest set of anagrams possible from all perfect squares of length K
- Check if all levels of two trees are anagrams or not
- Number of permutations of a string in which all the occurrences of a given character occurs together
- Minimum jumps required to group all 1s together in a given Binary string
- Print consecutive characters together in a line
- Count words that appear exactly two times in an array of words
- Check whether two strings are anagrams of each other using unordered_map in C++
- Find the word with most anagrams in a given sentence
- Print all valid words that are possible using Characters of Array
- Print all possible combinations of words from Dictionary using Trie
- Print all the non-repeating words from the two given sentences
- Rearrange a linked list such that all even and odd positioned nodes are together
- Check if all occurrences of a character appear together
- Minimum flips required to keep all 1s together in a Binary string

