Given a sequence of words, print all anagrams together | Set 1
Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.
A simple method is to create a Hash Table. Calculate the hash value of each word in such a way that all anagrams have the same hash value. Populate the Hash Table with these hash values. Finally, print those words together with the same hash values. A simple hashing mechanism can be modulo sum of all characters. With modulo sum, two non-anagram words may have the same hash value. This can be handled by matching individual characters.
Following is another method to print all anagrams together. Take two auxiliary arrays, index array, and word array. Populate the word array with the given sequence of words. Sort each individual word of the word array. Finally, sort the word array and keep track of the corresponding indices. After sorting, all the anagrams cluster together. Use the index array to print the strings from the original array of strings.
Let us understand the steps with the following input Sequence of Words:
"cat", "dog", "tac", "god", "act"
1) Create two auxiliary arrays index[] and words[]. Copy all given words to words[] and store the original indexes in index[]
index[]: 0 1 2 3 4
words[]: cat dog tac god act
2) Sort individual words in words[]. Index array doesn’t change.
index[]: 0 1 2 3 4
words[]: act dgo act dgo act
3) Sort the words array. Compare individual words using strcmp() to sort
index: 0 2 4 1 3
words[]: act act act dgo dgo
4) All anagrams come together. But words are changed in the words array. To print the original words, take the index from the index array and use it in the original array. We get
"cat tac act dog god"
Following are the implementations of the above algorithm. In the following program, an array of structure “Word” is used to store both index and word arrays. Dupray is another structure that stores an array of structure “Word”.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Word {
char * str;
int index;
};
struct DupArray {
struct Word* array;
int size;
};
struct DupArray* createDupArray( char * str[], int size)
{
struct DupArray* dupArray
= ( struct DupArray*) malloc ( sizeof ( struct DupArray));
dupArray->size = size;
dupArray->array = ( struct Word*) malloc (
dupArray->size * sizeof ( struct Word));
int i;
for (i = 0; i < size; ++i) {
dupArray->array[i].index = i;
dupArray->array[i].str
= ( char *) malloc ( strlen (str[i]) + 1);
strcpy (dupArray->array[i].str, str[i]);
}
return dupArray;
}
int compChar( const void * a, const void * b)
{
return *( char *)a - *( char *)b;
}
int compStr( const void * a, const void * b)
{
struct Word* a1 = ( struct Word*)a;
struct Word* b1 = ( struct Word*)b;
return strcmp (a1->str, b1->str);
}
void printAnagramsTogether( char * wordArr[], int size)
{
struct DupArray* dupArray
= createDupArray(wordArr, size);
int i;
for (i = 0; i < size; ++i)
qsort (dupArray->array[i].str,
strlen (dupArray->array[i].str), sizeof ( char ),
compChar);
qsort (dupArray->array, size, sizeof (dupArray->array[0]),
compStr);
for (i = 0; i < size; ++i)
printf ( "%s " , wordArr[dupArray->array[i].index]);
}
int main()
{
char * wordArr[] = { "cat" , "dog" , "tac" , "god" , "act" };
int size = sizeof (wordArr) / sizeof (wordArr[0]);
printAnagramsTogether(wordArr, size);
return 0;
}
|
C++
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
class Word {
public :
char * str;
int index;
};
class DupArray {
public :
Word* array;
int size;
};
DupArray* createDupArray( char * str[], int size)
{
DupArray* dupArray = new DupArray();
dupArray->size = size;
dupArray->array
= new Word[(dupArray->size * sizeof (Word))];
int i;
for (i = 0; i < size; ++i) {
dupArray->array[i].index = i;
dupArray->array[i].str
= new char [( strlen (str[i]) + 1)];
strcpy (dupArray->array[i].str, str[i]);
}
return dupArray;
}
int compChar( const void * a, const void * b)
{
return *( char *)a - *( char *)b;
}
int compStr( const void * a, const void * b)
{
Word* a1 = (Word*)a;
Word* b1 = (Word*)b;
return strcmp (a1->str, b1->str);
}
void printAnagramsTogether( char * wordArr[], int size)
{
DupArray* dupArray = createDupArray(wordArr, size);
int i;
for (i = 0; i < size; ++i)
qsort (dupArray->array[i].str,
strlen (dupArray->array[i].str), sizeof ( char ),
compChar);
qsort (dupArray->array, size, sizeof (dupArray->array[0]),
compStr);
for (i = 0; i < size; ++i)
cout << wordArr[dupArray->array[i].index] << " " ;
}
int main()
{
char * wordArr[] = { "cat" , "dog" , "tac" , "god" , "act" };
int size = sizeof (wordArr) / sizeof (wordArr[0]);
printAnagramsTogether(wordArr, size);
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Comparator;
public class GFG {
static class Word {
String str;
int index;
Word(String str, int index)
{
this .str = str;
this .index = index;
}
}
static class DupArray {
Word[] array;
int size;
public DupArray(String str[], int size)
{
this .size = size;
array = new Word[size];
int i;
for (i = 0 ; i < size; ++i) {
array[i] = new Word(str[i], i);
}
}
}
static class compStr implements Comparator<Word> {
public int compare(Word a, Word b)
{
return a.str.compareTo(b.str);
}
}
static void printAnagramsTogether(String wordArr[],
int size)
{
DupArray dupArray = new DupArray(wordArr, size);
int i;
for (i = 0 ; i < size; ++i) {
char [] char_arr
= dupArray.array[i].str.toCharArray();
Arrays.sort(char_arr);
dupArray.array[i].str = new String(char_arr);
}
Arrays.sort(dupArray.array, new compStr());
for (i = 0 ; i < size; ++i)
System.out.print(
wordArr[dupArray.array[i].index] + " " );
}
public static void main(String args[])
{
String wordArr[]
= { "cat" , "dog" , "tac" , "god" , "act" };
int size = wordArr.length;
printAnagramsTogether(wordArr, size);
}
}
|
Python
class Word( object ):
def __init__( self , string, index):
self .string = string
self .index = index
def createDupArray(string, size):
dupArray = []
for i in xrange (size):
dupArray.append(Word(string[i], i))
return dupArray
def printAnagramsTogether(wordArr, size):
dupArray = createDupArray(wordArr, size)
for i in xrange (size):
dupArray[i].string = ''.join( sorted (dupArray[i].string))
dupArray = sorted (dupArray, key = lambda k: k.string)
for word in dupArray:
print wordArr[word.index],
wordArr = [ "cat" , "dog" , "tac" , "god" , "act" ]
size = len (wordArr)
printAnagramsTogether(wordArr, size)
|
C#
using System;
using System.Linq;
class Word {
public string Str;
public int Index;
}
class DupArray {
public Word[] Array;
public int Size;
}
public class GFG {
static DupArray CreateDupArray( string [] str, int size)
{
var dupArray = new DupArray();
dupArray.Size = size;
dupArray.Array = new Word[dupArray.Size];
for ( var i = 0; i < size; i++) {
dupArray.Array[i] = new Word();
dupArray.Array[i].Index = i;
dupArray.Array[i].Str = str[i];
}
return dupArray;
}
static int CompStr(Word a, Word b)
{
return string .Compare( new string (a.Str.OrderBy(c => c).ToArray()), new string (b.Str.OrderBy(c => c).ToArray()));
}
static void PrintAnagramsTogether( string [] wordArr, int size)
{
var dupArray = CreateDupArray(wordArr, size);
Array.Sort(dupArray.Array, CompStr);
foreach ( var word in dupArray.Array)
{
Console.Write(wordArr[word.Index] + " " );
}
}
static public void Main( string [] args)
{
var wordArr = new string [] { "cat" , "dog" , "tac" , "god" , "act" };
var size = wordArr.Length;
PrintAnagramsTogether(wordArr, size);
}
}
|
Javascript
class Word {
constructor(string, index) {
this .string = string;
this .index = index;
}
}
function createDupArray(string, size) {
let dupArray = [];
for (let i = 0; i < size; i++) {
dupArray.push( new Word(string[i], i));
}
return dupArray;
}
function printAnagramsTogether(wordArr, size) {
let dupArray = createDupArray(wordArr, size);
for (let i = 0; i < size; i++) {
dupArray[i].string = dupArray[i].string.split( "" ).sort().join( "" );
}
dupArray = dupArray.sort((a, b) => a.string.localeCompare(b.string));
for (let word of dupArray) {
console.log(wordArr[word.index]);
}
}
let wordArr = [ "cat" , "dog" , "tac" , "god" , "act" ];
let size = wordArr.length;
printAnagramsTogether(wordArr, size);
|
Output:
cat tac act dog god
Time Complexity: Let there be N-words and each word has a maximum of M characters. The upper bound is O(NMLogM + MNLogN).
Step 2 takes O(NMLogM) time. Sorting a word takes maximum O(MLogM) time. So sorting N-words takes O(NMLogM) time. step 3 takes O(MNLogN) Sorting array of words takes NLogN comparisons. A comparison may take maximum O(M) time. So time to sort an array of words will be O(MNLogN).
Space complexity :- O(N*M)
Using vector of pair :
The problem can easily be solved with the use of a vector of pairs. The pair will be of string and int. The string will require to store the input string and int will require to store their respective indexes.
here is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#include <strings.h>
using namespace std;
void createDuplicateArray(
vector<pair<string, int > >& dupArray,
vector<string>& wordAr, int size)
{
for ( int i = 0; i < size; i++) {
dupArray.push_back(make_pair(wordAr[i], i));
}
}
void printAnagramsTogether(vector<string>& wordArr,
int size)
{
vector<pair<string, int > >
dupArray;
createDuplicateArray(
dupArray, wordArr,
size);
int i;
for (i = 0; i < size; ++i) {
sort(dupArray[i].first.begin(),
dupArray[i].first.end());
}
sort(dupArray.begin(), dupArray.end());
for (i = 0; i < size; ++i)
cout << wordArr[dupArray[i].second] << " " ;
}
int main()
{
vector<string> wordArr
= { "cat" , "dog" , "tac" , "god" , "act" };
printAnagramsTogether(wordArr, wordArr.size());
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Pair {
char word[100];
int index;
};
void createDuplicateArray( struct Pair dupArray[],
char * wordAr[], int size)
{
for ( int i = 0; i < size; i++) {
strcpy (dupArray[i].word, wordAr[i]);
dupArray[i].index = i;
}
}
void printAnagramsTogether( char * wordArr[], int size)
{
struct Pair dupArray[size];
createDuplicateArray(dupArray, wordArr, size);
int i;
for (i = 0; i < size; ++i) {
int len = strlen (dupArray[i].word);
qsort (dupArray[i].word, len, sizeof ( char ),
(__compar_fn_t) strcmp );
}
qsort (dupArray, size, sizeof ( struct Pair),
(__compar_fn_t) strcmp );
for (i = 0; i < size; ++i) {
printf ( "%s " , wordArr[dupArray[i].index]);
}
}
int main()
{
char * wordArr[] = { "cat" , "dog" , "tac" , "god" , "act" };
int size = sizeof (wordArr) / sizeof (wordArr[0]);
printAnagramsTogether(wordArr, size);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class Main {
static class Pair implements Comparable<Pair> {
String x;
int y;
public Pair(String x, int y)
{
this .x = x;
this .y = y;
}
public int compareTo(Pair o)
{
return this .x.compareTo(o.x);
}
}
static ArrayList<Pair>
createDuplicateArray(String[] wordArr, int size)
{
ArrayList<Pair> dupArray = new ArrayList<Pair>();
for ( int i = 0 ; i < size; i++) {
Pair p = new Pair(wordArr[i], i);
dupArray.add(p);
}
return dupArray;
}
static void printAnagramsTogether(String[] wordArr,
int size)
{
ArrayList<Pair> dupArray = new ArrayList<Pair>();
;
dupArray = createDuplicateArray(
wordArr, size);
for ( int i = 0 ; i < size; ++i) {
Pair e = dupArray.get(i);
char [] arr = e.x.toCharArray();
Arrays.sort(arr);
String x = String.valueOf(arr);
Pair p = new Pair(x, e.y);
dupArray.set(i, p);
}
Collections.sort(dupArray);
for ( int i = 0 ; i < size; ++i)
System.out.print(wordArr[dupArray.get(i).y]
+ " " );
}
public static void main(String[] args)
{
String[] wordArr
= { "cat" , "dog" , "tac" , "god" , "act" };
printAnagramsTogether(wordArr, wordArr.length);
}
}
|
Python3
from typing import List , Tuple
def create_duplicate_array(wordAr: List [ str ]) - > List [ Tuple [ str , int ]]:
dup_array = []
for i, word in enumerate (wordAr):
dup_array.append((word, i))
return dup_array
def print_anagrams_together(wordArr: List [ str ]):
dup_array = create_duplicate_array(wordArr)
for i in range ( len (wordArr)):
dup_array[i] = ( sorted (dup_array[i][ 0 ]), dup_array[i][ 1 ])
dup_array.sort()
for i in range ( len (wordArr)):
print (wordArr[dup_array[i][ 1 ]], end = ' ' )
wordArr = [ "cat" , "dog" , "tac" , "god" , "act" ]
print_anagrams_together(wordArr)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
class Pair : IComparable<Pair> {
public string x;
public int y;
public Pair( string x, int y)
{
this .x = x;
this .y = y;
}
public int CompareTo(Pair other)
{
return this .x.CompareTo(other.x);
}
}
static List<Pair> CreateDuplicateArray( string [] wordArr,
int size)
{
List<Pair> dupArray = new List<Pair>();
for ( int i = 0; i < size; i++) {
Pair p = new Pair(wordArr[i], i);
dupArray.Add(p);
}
return dupArray;
}
static void PrintAnagramsTogether( string [] wordArr,
int size)
{
List<Pair> dupArray
= CreateDuplicateArray(wordArr, size);
for ( int i = 0; i < size; i++) {
Pair e = dupArray[i];
char [] arr = e.x.ToCharArray();
Array.Sort(arr);
string x = new string (arr);
Pair p = new Pair(x, e.y);
dupArray[i] = p;
}
dupArray.Sort();
for ( int i = 0; i < size; i++) {
Console.Write(wordArr[dupArray[i].y] + " " );
}
}
static public void Main( string [] args)
{
string [] wordArr
= { "cat" , "dog" , "tac" , "god" , "act" };
PrintAnagramsTogether(wordArr, wordArr.Length);
}
}
|
Javascript
var wordArr = [ "cat" , "dog" , "tac" , "god" , "act" ];
function createDuplicateArray(wordArr, size) {
var dupArray = [];
for ( var i = 0; i < size; i++) {
var pair = {
x: wordArr[i],
y: i
};
dupArray.push(pair);
}
return dupArray;
}
function printAnagramsTogether(wordArr, size) {
var dupArray = createDuplicateArray(wordArr, size);
for ( var i = 0; i < size; i++) {
var word = dupArray[i].x;
word = word.split( "" ).sort().join( "" );
dupArray[i].x = word;
}
dupArray.sort( function (a, b) {
return a.x.localeCompare(b.x);
});
for ( var i = 0; i < size; i++) {
console.log(wordArr[dupArray[i].y]);
}
}
printAnagramsTogether(wordArr, wordArr.length);
|
Output
cat tac act dog god
Time complexity:
Let there be N-words and each word has a maximum of M characters.
O(NMLogM + MNLogN).
Space complexity :- O(N)
Using Hashmap
Here, we first sort each word, use the sorted word as a key and then put an original word on a map. The value of the map will be a list containing all the words which have the same word after sorting.
Lastly, we will print all values from the hashmap where the size of values will be greater than 1.
C++
#include <bits/stdc++.h>
using namespace std;
void printAnagrams(string arr[], int size)
{
unordered_map<string, vector<string> > map;
for ( int i = 0; i < size; i++) {
string word = arr[i];
char letters[word.size() + 1];
strcpy (letters, word.c_str());
sort(letters, letters + word.size() + 1);
string newWord = "" ;
for ( int i = 0; i < word.size() + 1; i++) {
newWord += letters[i];
}
if (map.find(newWord) != map.end()) {
map[newWord].push_back(word);
}
else {
vector<string> words;
words.push_back(word);
map[newWord] = words;
}
}
unordered_map<string, vector<string> >::iterator it;
for (it = map.begin(); it != map.end(); it++) {
vector<string> values = map[it->first];
if (values.size() > 1) {
cout << "[" ;
for ( int i = 0; i < values.size() - 1; i++) {
cout << values[i] << ", " ;
}
cout << values[values.size() - 1];
cout << "]" ;
}
}
}
int main()
{
string arr[] = { "cat" , "dog" , "tac" , "god" , "act" };
int size = sizeof (arr) / sizeof (arr[0]);
printAnagrams(arr, size);
return 0;
}
|
Java
import java.util.*;
public class FindAnagrams {
private static void printAnagrams(String arr[])
{
HashMap<String, List<String> > map
= new HashMap<>();
for ( int i = 0 ; i < arr.length; i++) {
String word = arr[i];
char [] letters = word.toCharArray();
Arrays.sort(letters);
String newWord = new String(letters);
if (map.containsKey(newWord)) {
map.get(newWord).add(word);
}
else {
List<String> words = new ArrayList<>();
words.add(word);
map.put(newWord, words);
}
}
for (String s : map.keySet()) {
List<String> values = map.get(s);
if (values.size() > 1 ) {
System.out.print(values);
}
}
}
public static void main(String[] args)
{
String arr[]
= { "cat" , "dog" , "tac" , "god" , "act" };
printAnagrams(arr);
}
}
|
Python3
from collections import defaultdict
def printAnagramsTogether(words):
groupedWords = defaultdict( list )
for word in words:
groupedWords["".join( sorted (word))].append(word)
for group in groupedWords.values():
print ( " " .join(group))
if __name__ = = "__main__" :
arr = [ "cat" , "dog" , "tac" , "god" , "act" ]
printAnagramsTogether(arr)
|
C#
using System;
using System.Collections.Generic;
class GFG {
private static void printAnagrams(String[] arr)
{
Dictionary<String, List<String> > map
= new Dictionary<String, List<String> >();
for ( int i = 0; i < arr.Length; i++) {
String word = arr[i];
char [] letters = word.ToCharArray();
Array.Sort(letters);
String newWord = new String(letters);
if (map.ContainsKey(newWord)) {
map[newWord].Add(word);
}
else {
List<String> words = new List<String>();
words.Add(word);
map.Add(newWord, words);
}
}
List<String> value = new List<String>();
foreach (KeyValuePair<String, List<String> > entry in
map)
{
value.Add(entry.Key);
}
int k = 0;
foreach (KeyValuePair<String, List<String> > entry in
map)
{
List<String> values = map[value[k++]];
if (values.Count > 1) {
Console.Write( "[" );
int len = 1;
foreach (String s in values)
{
Console.Write(s);
if (len++ < values.Count)
Console.Write( ", " );
}
Console.Write( "]" );
}
}
}
public static void Main(String[] args)
{
String[] arr
= { "cat" , "dog" , "tac" , "god" , "act" };
printAnagrams(arr);
}
}
|
Javascript
function printAnagrams(arr) {
const map = {};
for (let i = 0; i < arr.length; i++) {
let word = arr[i];
let letters = word.split( "" );
letters.sort();
let newWord = letters.join( "" );
if (map[newWord]) {
map[newWord].push(word);
} else {
const words = [];
words.push(word);
map[newWord] = words;
}
}
for (const s in map) {
const values = map[s];
if (values.length > 1) {
console.log(values);
}
}
}
const arr = [ "cat" , "dog" , "tac" , "god" , "act" ];
printAnagrams(arr);
|
Output
[dog, god][cat, tac, act]
Time Complexity : O(N x M x logM + N).
Auxiliary space: O(M x N).
HashMap with O(NM) Solution
In the previous approach, we were sorting every string in order to maintain a similar key, but that cost extra time in this approach will take the advantage of another hashmap to maintain the frequency of the characters which will generate the same hash function for different string having same frequency of characters.
Here, we will take HashMap<HashMap, ArrayList>, the inner hashmap will count the frequency of the characters of each string and the outer HashMap will check whether that hashmap is present or not if present then it will add that string to the corresponding list.
C++
#include <bits/stdc++.h>
using namespace std;
void solver(vector<string> my_list)
{
map<map< char , int >, vector<string>> my_map;
for (string str : my_list)
{
map< char , int > temp_map;
vector<string> temp_my_list;
for ( int i = 0; i < str.length(); ++i)
{
++temp_map[str[i]];
}
auto it = my_map.find(temp_map);
if (it != my_map.end())
{
it->second.push_back(str);
}
else
{
temp_my_list.push_back(str);
my_map.insert({ temp_map, temp_my_list });
}
}
vector<vector<string>> result;
for ( auto it = my_map.begin();
it != my_map.end(); ++it)
{
result.push_back(it->second);
}
for ( int i = 0; i < result.size(); ++i)
{
cout << "[" ;
for ( int j = 0; j < result[i].size()-1; ++j)
{
cout << result[i][j] << ", " ;
}
cout<< result[i][result[i].size()-1];
cout << "]" ;
}
}
int main()
{
vector<string> my_list = { "cat" , "dog" , "ogd" ,
"god" , "atc" };
solver(my_list);
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.HashMap;
public class FindAnagrams {
private static ArrayList<ArrayList<String> >
solver(
ArrayList<String> list)
{
HashMap<HashMap<Character, Integer>,
ArrayList<String> >
map = new HashMap<HashMap<Character, Integer>,
ArrayList<String> >();
for (String str : list) {
HashMap<Character, Integer>
tempMap = new HashMap<Character, Integer>();
for ( int i = 0 ; i < str.length(); i++) {
if (tempMap.containsKey(str.charAt(i))) {
int x = tempMap.get(str.charAt(i));
tempMap.put(str.charAt(i), ++x);
}
else {
tempMap.put(str.charAt(i), 1 );
}
}
if (map.containsKey(tempMap))
map.get(tempMap).add(str);
else {
ArrayList<String>
tempList = new ArrayList<String>();
tempList.add(str);
map.put(tempMap, tempList);
}
}
ArrayList<ArrayList<String> >
result = new ArrayList<>();
for (HashMap<Character, Integer>
temp : map.keySet())
result.add(map.get(temp));
return result;
}
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<>();
list.add( "cat" );
list.add( "dog" );
list.add( "ogd" );
list.add( "god" );
list.add( "atc" );
System.out.println(solver(list));
}
}
|
Python3
from collections import Counter, defaultdict
user_input = [ "cat" , "dog" , "tac" , "edoc" , "god" , "tacact" ,
"act" , "code" , "deno" , "node" , "ocde" , "done" , "catcat" ]
def solve(words: list ) - > list :
m = defaultdict( list )
for word in words:
m[ frozenset ( dict (Counter(word)).items())].append(word)
return [v for k, v in m.items()]
print (solve(user_input))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main( string [] args)
{
List< string > myList = new List< string >() {
"cat" , "dog" , "ogd" , "god" , "atc"
};
Solver(myList);
}
static void Solver(List< string > myList)
{
Dictionary< string , List< string > > myMap
= new Dictionary< string , List< string > >();
foreach ( string str in myList)
{
char [] arr = str.ToCharArray();
Array.Sort(arr);
string sortedStr = new string (arr);
if (myMap.ContainsKey(sortedStr)) {
myMap[sortedStr].Add(str);
}
else {
List< string > tempList
= new List< string >() { str };
myMap.Add(sortedStr, tempList);
}
}
List<List< string > > result
= new List<List< string > >();
foreach (KeyValuePair< string , List< string > > kvp in
myMap)
{
result.Add(kvp.Value);
}
foreach (List< string > list in result)
{
Console.Write( "[" );
Console.Write(String.Join( ", " , list));
Console.Write( "] " );
}
Console.WriteLine();
}
}
|
Javascript
let user_input = [ "cat" , "dog" , "tac" , "edoc" , "god" , "tacact" ,
"act" , "code" , "deno" , "node" , "ocde" , "done" , "catcat" ];
function solve(words) {
let m = new Map();
for (let word of words) {
let charCount = new Map();
for (let char of word) {
charCount.set(char, (charCount.get(char) || 0) + 1);
}
let key = JSON.stringify([...charCount.entries()].sort());
let values = m.get(key) || [];
values.push(word);
m.set(key, values);
}
return [...m.values()];
}
console.log(solve(user_input));
|
Output
[cat, atc, ][dog, ogd, god, ]
Time Complexity: Let there be N-words and each word has a maximum of M characters. The upper bound is O(NM).
Space Complexity: Let there be N-words and each word has maximum M characters, therefore max. storage space for each word with at max. M characters will be O(M), therefore for max N-words, it will be O(N*M). Therefore, the upper bound is O(NM).
This article is contributed by Aarti_Rathi and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org.
Given a sequence of words, print all anagrams together | Set 2
Last Updated :
23 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...