Skip to content

Commit 53ce9c4

Browse files
authored
Merge pull request #1187 from maradadivyasree020/lc-49
lc-0049 solution added
2 parents b396dbe + 886f2e9 commit 53ce9c4

File tree

1 file changed

+144
-0
lines changed

1 file changed

+144
-0
lines changed
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
---
2+
id: group-anagrams
3+
title: Group Anagrams (LeetCode)
4+
sidebar_label: 0049-Group Anagrams
5+
tags:
6+
- Array
7+
- Hash Table
8+
- String
9+
- Sorting
10+
description: Given an array of strings , group the anagrams together.
11+
sidebar_position: 0049
12+
---
13+
14+
## Problem Description
15+
16+
The task is to write a function that takes an array (list) of strings called strs and groups the anagrams together. An anagram is a word obtained by rearranging the letters of another word to form a new word using all the original characters exactly once. For example, "taste" and "state" are anagrams of each other. The function can return the groups in any order, meaning the sequence of the groups is not important, and within each group, the sequence of strings is not important either.
17+
18+
### Example 1
19+
20+
- **Input:** `strs = ["eat","tea","tan","ate","nat","bat"]`
21+
- **Output:** `[["bat"],["nat","tan"],["ate","eat","tea"]]`
22+
- **Explanation:**
23+
- ["ate", "eat","tea"](when sorted all these strings are "aet"),
24+
- ["nat","tan"](when sorted all these strings are "ant"),
25+
- ["bat"](this string has no other string as anagram so it is appended as only 1)
26+
27+
### Example 2
28+
29+
- **Input:** ` strs = [""]`
30+
- **Output:** `[[""]]`
31+
- **Explanation:** There are no strings so empty vector is returned.
32+
33+
### Example 3
34+
35+
- **Input:** ` strs = ["a"]`
36+
- **Output:** `[["a"]]`
37+
- **Explanation:** There is only one string "a" it is returned.
38+
39+
### Constraints
40+
41+
- `1 <= strs.length <= 10^4`
42+
- `0 <= strs[i].length <= 100`
43+
- `strs[i] consists of lowercase English letters.`
44+
45+
## Approach
46+
- 1. Create a defaultdict of lists: d = defaultdict(list). This will store our anagrams.
47+
48+
- 2. Iterate through each string in the array:
49+
50+
- "bat": When sorted, becomes "abt". We append "bat" to d["abt"].
51+
- "ate": When sorted, becomes "aet". We append "ate" to d["aet"].
52+
- "eat": When sorted, becomes "aet". We append "eat" to d["aet"].
53+
- "tea": When sorted, becomes "aet". We append "tea" to d["aet"].
54+
- "tan": When sorted, becomes "ant". We append "tan" to d["ant"].
55+
- "nat": When sorted, becomes "ant". We append "nat" to d["ant"].
56+
- 3. Now, d looks like this: `{
57+
"abt": ["bat" ],
58+
"aet": ["eat", "tea" , "ate"],
59+
"ant": ["tan", "nat"]
60+
}`
61+
- Each key corresponds to a sorted string, and the values are the original strings that are anagrams.
62+
63+
- 4. Finally, we return the dictionary values as a list of lists:
64+
65+
- [
66+
["bat"],
67+
["eat", "tea" , "ate"],
68+
["tan", "nat"]
69+
]
70+
71+
### Solution Code
72+
73+
#### Python
74+
75+
```python
76+
class Solution:
77+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
78+
anagrams = defaultdict(list)
79+
for s in strs:
80+
key = "".join(sorted(s))
81+
anagrams[key].append(s)
82+
return list(anagrams.values())
83+
```
84+
85+
#### C++
86+
```c++
87+
class Solution {
88+
public:
89+
vector<vector<string>> groupAnagrams(vector<string>& strs) {
90+
unordered_map<string, vector<string>> anagramGroups;
91+
for (auto& str : strs) {
92+
string key = str;
93+
sort(key.begin(), key.end());
94+
anagramGroups[key].emplace_back(str);
95+
}
96+
vector<vector<string>> groupedAnagrams;
97+
for (auto& pair : anagramGroups) {
98+
groupedAnagrams.emplace_back(pair.second);
99+
}
100+
return groupedAnagrams;
101+
}
102+
};
103+
```
104+
105+
#### Java
106+
```Java
107+
import java.util.*;
108+
109+
class Solution {
110+
public List<List<String>> groupAnagrams(String[] strs) {
111+
Map<String, List<String>> anagramsMap = new HashMap<>();
112+
for (String str : strs) {
113+
char[] charArray = str.toCharArray();
114+
Arrays.sort(charArray);
115+
String sortedStr = String.valueOf(charArray);
116+
anagramsMap.computeIfAbsent(sortedStr, key -> new ArrayList<>()).add(str);
117+
}
118+
return new ArrayList<>(anagramsMap.values());
119+
}
120+
}
121+
122+
```
123+
124+
125+
126+
127+
#### Conclusion
128+
- Time Complexity
129+
The time complexity of the code is primarily determined by two operations: the sorting operation for each string and the insertion into the dictionary.
130+
131+
- 1. Sorting Each String: Assuming the average length of the strings is n and there are m strings to sort, the time complexity of sorting each is O(n log n). Since we need to sort m such strings, the total time complexity for this part is O(m * n log n).
132+
133+
- 2. Inserting into Dictionary: The insertion of m strings into the dictionary has a time complexity of O(m), since each insertion operation into a dictionary is O(1) on average.
134+
135+
- The total time complexity as O(m * n log n).
136+
137+
- Space Complexity
138+
The space complexity is due to the storage of m entries in the dictionary and the lists of anagrams.
139+
140+
- 1. Dictionary Storage (HashMap): The dictionary stores lists of anagrams. In the worst case, all strings are anagrams of each other, requiring O(m * n) space (since each of the m strings of length n can be in the same list).
141+
142+
- 2. Sorted String Keys: Additionally, for each string, we create a sorted copy to use as a key. Since we sort each string in place and only have m keys at any point in time, the space for the keys would be O(m * n).
143+
144+
- The total space complexity of the algorithm is O(m * n),

0 commit comments

Comments
 (0)