Skip to content

Commit 85bbf05

Browse files
committed
Add same Neetcode question to Leetcode folder
1 parent 0ec8095 commit 85bbf05

File tree

2 files changed

+170
-0
lines changed

2 files changed

+170
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Neetcode
2+
class Solution:
3+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
4+
5+
# # Step 1
6+
# anagrams = defaultdict(list) # Initialize a dictionary to hold lists of anagrams
7+
8+
# # Iterate over each word in the list
9+
# for word in strs:
10+
# # Sort the characters of the word to use as the key
11+
# sorted_word = ''.join(sorted(word))
12+
# # Group anagrams together using the sorted word as the key
13+
# anagrams[sorted_word].append(word)
14+
15+
# # Convert the dictionary values (which are lists of anagrams) to a list of lists
16+
# return list(anagrams.values())
17+
18+
# # Step 2:
19+
ans = collections.defaultdict(list)
20+
21+
for s in strs:
22+
count = [0] * 26
23+
for c in s:
24+
count[ord(c) - ord("a")] += 1
25+
ans[tuple(count)].append(s)
26+
return ans.values()
27+
28+
29+
# Leetcode
30+
class Solution(object):
31+
def groupAnagrams(self, strs):
32+
"""
33+
:type strs: List[str]
34+
:rtype: List[List[str]]
35+
"""
36+
# # Step 1
37+
# anagrams = defaultdict(list) # Initialize a dictionary to hold lists of anagrams
38+
39+
# # Iterate over each word in the list
40+
# for word in strs:
41+
# # Sort the characters of the word to use as the key
42+
# sorted_word = ''.join(sorted(word))
43+
# # Group anagrams together using the sorted word as the key
44+
# anagrams[sorted_word].append(word)
45+
46+
# # Convert the dictionary values (which are lists of anagrams) to a list of lists
47+
# return list(anagrams.values())
48+
49+
# # Step 2:
50+
ans = collections.defaultdict(list)
51+
52+
for s in strs:
53+
count = [0] * 26
54+
for c in s:
55+
count[ord(c) - ord("a")] += 1
56+
ans[tuple(count)].append(s)
57+
return ans.values()

Leetcode/Group_Anagrams/README.md

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
# Group Anagrams (Medium)
2+
3+
## Table of Contents
4+
5+
- [Problem Statement](#problem-statement)
6+
- [Examples](#examples)
7+
- [Constraints](#constraints)
8+
- [Solutions](#solutions)
9+
- [Approach 1: Using Sorted Strings as Keys](#approach-1-using-sorted-strings-as-keys)
10+
- [Approach 2: Hash Map with Character Count as Key](#approach-2-hash-map-with-character-count-as-key)
11+
- [Complexity Analysis](#complexity-analysis)
12+
- [Code Explanation](#code-explanation)
13+
- [Related Resources](#related-resources)
14+
15+
## Problem Statement
16+
17+
Given an array of strings `strs`, group all anagrams together into sublists. You may return the output in any order.
18+
19+
An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
20+
21+
- [View on Neetcode.io](https://neetcode.io/problems/anagram-groups)
22+
- [View on LeetCode](https://leetcode.com/problems/group-anagrams/description/)
23+
24+
## Examples
25+
26+
**Example 1:**
27+
```
28+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
29+
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
30+
```
31+
32+
**Example 2:**
33+
```
34+
Input: strs = [""]
35+
Output: [[""]]
36+
```
37+
38+
**Example 3:**
39+
```
40+
Input: strs = ["a"]
41+
Output: [["a"]]
42+
```
43+
44+
## Constraints
45+
46+
- $1 \leq strs.length \leq 10^4$
47+
- $0 \leq strs[i].length \leq 100$
48+
- `strs[i]` consists of lowercase English letters.
49+
50+
## Solutions
51+
52+
### Approach 1: Using Sorted Strings as Keys
53+
54+
```python
55+
class Solution:
56+
def twoSum(self, nums: List[int], target: int) -> List[int]:
57+
if len(nums) == 2:
58+
return [0, 1]
59+
for i in range(len(nums)):
60+
for j in range(i + 1, len(nums)):
61+
if nums[i] + nums[j] == target:
62+
if nums.index(nums[i]) == nums.index(nums[j]):
63+
return [nums.index(nums[i]), nums.index(nums[j], i + 1, len(nums))]
64+
return [nums.index(nums[i]), nums.index(nums[j])]
65+
```
66+
67+
### Approach 2: Hash Map with Character Count as Key
68+
69+
```python
70+
class Solution:
71+
def twoSum(self, nums: List[int], target: int) -> List[int]:
72+
seenMap = {}
73+
for i in range(len(nums)):
74+
remain = target - nums[i]
75+
if remain in seenMap:
76+
return [seenMap[remain], i]
77+
seenMap[nums[i]] = i
78+
return nums
79+
```
80+
81+
## Complexity Analysis
82+
83+
### Approach 1:
84+
- Time Complexity: $O(N * M * \log(M))$, where N is the number of strings and M is the maximum length of a string.
85+
- Space Complexity: $O(N * M)$
86+
87+
### Approach 2:
88+
- Time Complexity: $O(N * M)$, where N is the number of strings and M is the maximum length of a string.
89+
- Space Complexity: $O(N * M)$
90+
91+
## Code Explanation
92+
93+
### Approach 1: Using Sorted Strings as Keys
94+
This approach involves sorting each string and using the sorted string as a key in a dictionary.
95+
96+
### Approach 2: Hash Map with Character Count as Key
97+
This solution uses a hash map to group anagrams:
98+
1. We iterate through each string in the input array.
99+
2. For each string, we create a key by counting the occurrences of each character.
100+
3. We use this count as a key in our hash map. The value is a list of all strings that have the same character count.
101+
4. Finally, we return the values of the hash map, which are the grouped anagrams.
102+
103+
This approach is efficient and passes on both Neetcode.io and LeetCode.
104+
105+
## Related Resources
106+
107+
- [Neetcode Solution](https://github.com/neetcode-gh/leetcode/blob/main/python/0049-group-anagrams.py)
108+
- [LeetCode Solution](https://leetcode.com/problems/group-anagrams/solutions/5729062/solution)
109+
- [Personal Submission](https://leetcode.com/submissions/detail/1377240624/)
110+
- [Video Explanation (Neetcode)](https://youtu.be/vzdNOK2oB2E?si=aFbSKVZz4WfzrNg1)
111+
112+
> [!NOTE]
113+
> This problem is part of a larger collection following the roadmap on [Neetcode Roadmap](https://neetcode.io/roadmap). For more details and related problems, please refer to the Neetcode.io website.

0 commit comments

Comments
 (0)