diff --git a/Chapter-10-Sorting-and-Searching/10.2-Group-Anagrams/10.2-Group-Anagrams.cpp b/Chapter-10-Sorting-and-Searching/10.2-Group-Anagrams/10.2-Group-Anagrams.cpp new file mode 100644 index 0000000..9b6461d --- /dev/null +++ b/Chapter-10-Sorting-and-Searching/10.2-Group-Anagrams/10.2-Group-Anagrams.cpp @@ -0,0 +1,66 @@ +// Question 10.2 +// Group Anagrams +// +// Explanation: +// To check if two strings are anagrams of each other, we use a simple function that sorts them (by character) and +// checks if they are the same string. To sort the string array we start from the leftmost element and compare it to +// all other elements, moving all the anagrams to the right of it. Then we go to the first element that isn't an +// anagram of these and do the same process until we reach the end of the array. + +#include +using namespace std; + +vector > groupAnagrams(vector& strs) +{ + vector> result ; + + unordered_map> mp ; + + for(string c : strs ) + { + string s= c ; + sort(s.begin() , s.end()) ; + + mp[s].push_back(c) ; + } + + for(auto c : mp) + { + result.push_back(c.second) ; + } + + return result ; +} + +int main() +{ + int test_cases; + cin>>test_cases ; + while(test_cases) + { + int n; + cin>>n ; + vector str_list(n) ; + for(int i=0 ; i>str_list[i] ; + } + + vector> Ans = groupAnagrams(str_list) ; + + //sorting the Ans-Vector which contains our Grouped Anagrams + sort(Ans.begin() , Ans.end()); + + //Printing the Groups + for(int i=0 ; i