Skip to content

Commit 2b89554

Browse files
committed
print anagram
1 parent 3125364 commit 2b89554

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

DSA Crack Sheet/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@
8787
- [Program to generate all possible valid IP addresses from given string](https://www.geeksforgeeks.org/program-generate-possible-valid-ip-addresses-given-string/ "view topic")
8888
- [Smallest distinct window](https://practice.geeksforgeeks.org/problems/smallest-distant-window3132/1 "view question") - [Cpp Solution](./solutions/Smallest%20distinct%20window.cpp)
8989
- [Rearrange characters](https://practice.geeksforgeeks.org/problems/rearrange-characters/0# "view question") - [Cpp Solution](./solutions/Rearrange%20characters.cpp)
90+
- [Minimum characters to be added at front to make string palindrome](https://www.geeksforgeeks.org/minimum-characters-added-front-make-string-palindrome/ "view topic")
91+
- [Print Anagrams Together](https://practice.geeksforgeeks.org/problems/print-anagrams-together/1# "view question") - [Cpp Solution](./solutions/Print%20Anagrams%20Together.cpp)
9092
- []( "view question") - [Cpp Solution](./solutions/.cpp)
9193

9294
### Searching & Sorting
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
Print Anagrams Together
3+
=======================
4+
5+
Given an array of strings, return all groups of strings that are anagrams. The groups must be created in order of their appearance in the original array. Look at the sample case for clarification.
6+
7+
Example 1:
8+
Input:
9+
N = 5
10+
words[] = {act,god,cat,dog,tac}
11+
Output:
12+
god dog
13+
act cat tac
14+
Explanation:
15+
There are 2 groups of
16+
anagrams "god", "dog" make group 1.
17+
"act", "cat", "tac" make group 2.
18+
19+
Example 2:
20+
Input:
21+
N = 3
22+
words[] = {no,on,is}
23+
Output:
24+
no on
25+
is
26+
Explanation:
27+
There are 2 groups of
28+
anagrams "no", "on" make group 1.
29+
"is" makes group 2.
30+
31+
Your Task:
32+
The task is to complete the function Anagrams() that takes a list of strings as input and returns a list of groups such that each group consists of all the strings that are anagrams.
33+
34+
Expected Time Complexity: O(N*|S|*log|S|), where |S| is the length of the strings.
35+
Expected Auxiliary Space: O(N*|S|), where |S| is the length of the strings.
36+
37+
Constraints:
38+
1<=N<=100
39+
*/
40+
41+
vector<vector<string>> Anagrams(vector<string> &string_list)
42+
{
43+
vector<vector<string>> ans;
44+
unordered_map<string, vector<string>> hash;
45+
46+
for (auto &i : string_list)
47+
{
48+
string ana = i;
49+
sort(ana.begin(), ana.end());
50+
hash[ana].push_back(i);
51+
}
52+
53+
for (auto &i : hash)
54+
ans.push_back(i.second);
55+
return ans;
56+
}

0 commit comments

Comments
 (0)