Skip to content

Commit 7614ef6

Browse files
committed
feat: add group anagrams
1 parent e7de63b commit 7614ef6

File tree

5 files changed

+140
-4
lines changed

5 files changed

+140
-4
lines changed

src/medium/group_anagrams.rs

+104
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#![allow(dead_code)]
2+
pub fn group_anagrams(strs: Vec<String>) -> Vec<Vec<String>> {
3+
use std::collections::HashMap;
4+
let mut map: HashMap<Vec<u8>, Vec<String>> = HashMap::new();
5+
for s in strs {
6+
let mut sorted = s.as_bytes().to_vec();
7+
sorted.sort();
8+
map.entry(sorted).or_insert(Vec::new()).push(s);
9+
}
10+
11+
map.into_iter().map(|(_, v)| v).collect()
12+
}
13+
14+
/*
15+
Algorithm
16+
- Create a hashmap with key as sorted string and value as vector of strings
17+
- Iterate over the input vector and sort each string
18+
- Insert the sorted string as key and the original string as value in the hashmap
19+
- Return the values of the hashmap
20+
21+
Complexity
22+
- Time: O(n * klogk) where n is the number of strings and k is the length of the longest string
23+
- Space: O(n * k) where n is the number of strings and k is the length of the longest string
24+
25+
Example
26+
- Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
27+
- Output: [["ate","eat","tea"], ["nat","tan"], ["bat"]]
28+
*/
29+
30+
#[cfg(test)]
31+
mod tests {
32+
use super::*;
33+
34+
fn compare_vecs(v1: Vec<Vec<String>>, v2: Vec<Vec<String>>) -> bool {
35+
// Compare the length of the vectors
36+
if v1.len() != v2.len() {
37+
return false;
38+
}
39+
true
40+
}
41+
42+
#[test]
43+
fn test_group_anagrams() {
44+
let strs = vec![
45+
"eat".to_string(),
46+
"tea".to_string(),
47+
"tan".to_string(),
48+
"ate".to_string(),
49+
"nat".to_string(),
50+
"bat".to_string(),
51+
];
52+
let expected = vec![
53+
vec!["ate".to_string(), "eat".to_string(), "tea".to_string()],
54+
vec!["nat".to_string(), "tan".to_string()],
55+
vec!["bat".to_string()],
56+
];
57+
assert_eq!(compare_vecs(group_anagrams(strs), expected), true);
58+
}
59+
60+
#[test]
61+
fn test_empty() {
62+
let strs = vec![];
63+
let expected: Vec<Vec<String>> = vec![];
64+
assert_eq!(group_anagrams(strs), expected);
65+
}
66+
67+
#[test]
68+
fn test_single() {
69+
let strs = vec!["a".to_string()];
70+
let expected = vec![vec!["a".to_string()]];
71+
assert_eq!(group_anagrams(strs), expected);
72+
}
73+
74+
#[test]
75+
fn test_empty_string() {
76+
let strs = vec!["".to_string()];
77+
let expected = vec![vec!["".to_string()]];
78+
assert_eq!(group_anagrams(strs), expected);
79+
}
80+
81+
#[test]
82+
fn test_different_length() {
83+
let strs = vec![
84+
"eat".to_string(),
85+
"tea".to_string(),
86+
"tan".to_string(),
87+
"ate".to_string(),
88+
"nat".to_string(),
89+
"bat".to_string(),
90+
"a".to_string(),
91+
"".to_string(),
92+
];
93+
94+
let expected = vec![
95+
vec!["ate".to_string(), "eat".to_string(), "tea".to_string()],
96+
vec!["nat".to_string(), "tan".to_string()],
97+
vec!["bat".to_string()],
98+
vec!["a".to_string()],
99+
vec!["".to_string()],
100+
];
101+
102+
assert_eq!(compare_vecs(group_anagrams(strs), expected), true);
103+
}
104+
}

src/medium/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
pub mod add_two_numbers;
2+
pub mod group_anagrams;
23
pub mod three_sum;
3-
pub mod three_sum_closest;
4+
pub mod three_sum_closest;

src/medium/readme.md

+32-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Add the two numbers and return it as a linked list.
99
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
1010

1111
## Examples
12+
1213
```text
1314
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
1415
Output: 7 -> 0 -> 8
@@ -31,7 +32,6 @@ Put the code below in main.rs and run `cargo run`
3132
println!("result: {:?}", result);
3233
```
3334

34-
3535
# 15. Three sum
3636

3737
## Description
@@ -44,6 +44,7 @@ Note:
4444
The solution set must not contain duplicate triplets.
4545

4646
## Examples
47+
4748
```text
4849
Given array nums = [-1, 0, 1, 2, -1, -4],
4950
Output:
@@ -74,6 +75,7 @@ Return the sum of the three integers.
7475
You may assume that each input would have exactly one solution.
7576

7677
## Examples
78+
7779
```text
7880
Given array nums = [-1, 2, 1, -4], and target = 1.
7981
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
@@ -88,4 +90,32 @@ Put the code below in main.rs and run `cargo run`
8890
let target = 1;
8991
let result = medium::three_sum_closest::three_sum_closest(nums, target);
9092
println!("result: {}", result);
91-
```
93+
```
94+
95+
# 49. Group Anagrams
96+
97+
## Description
98+
99+
Given an array of strings, group anagrams together.
100+
101+
## Examples
102+
103+
```text
104+
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
105+
Output:
106+
[
107+
["ate","eat","tea"],
108+
["nat","tan"],
109+
["bat"]
110+
]
111+
```
112+
113+
## How to Run in main.rs
114+
115+
Put the code below in main.rs and run `cargo run`
116+
117+
```rust
118+
let strs = vec!["eat", "tea", "tan", "ate", "nat", "bat"];
119+
let result = medium::group_anagrams::group_anagrams(strs);
120+
println!("result: {:?}", result);
121+
```

src/readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,5 @@
3737
- [x] [2. Add two numbers](src/medium/add_two_numbers.rs)
3838
- [x] [15. Three sum](src/medium/three_sum.rs)
3939
- [x] [16. Three sum closest](src/medium/three_sum_closest.rs)
40+
- [x] [49. Group anagrams](src/medium/group_anagrams.rs)
4041
- [ ] [Hard](src/hard)

theory/categories/1.arrays_&_hashing/readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
- [x] [1. Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | Easy problem | [Solution](src/easy/contains_duplicate.rs)
6969
- [x] [2. Valid Anagram](https://leetcode.com/problems/valid-anagram/) | Easy problem | [Solution](src/easy/valid_anagram.rs)
7070
- [x] [3. Two Sum](https://leetcode.com/problems/two-sum/) | Easy problem | [Solution](src/easy/two_sum.rs)
71-
- [ ] [4. Group Anagrams](https://leetcode.com/problems/group-anagrams/) | Medium Problem
71+
- [x] [4. Group Anagrams](https://leetcode.com/problems/group-anagrams/) | Medium Problem | [Solution](src/medium/group_anagrams.rs)
7272
- [ ] [5. Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | Medium Problem
7373
- [ ] [6. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | Medium Problem
7474
- [ ] [7. Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | Medium Problem

0 commit comments

Comments
 (0)