Skip to content

Commit b5bad51

Browse files
committed
updates
1 parent 79266a5 commit b5bad51

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"""
2+
Problem:
3+
-----------------------------------------------
4+
https://leetcode.com/problems/contains-duplicate-ii/
5+
"""
6+
7+
8+
class Solution:
9+
def containsNearbyDuplicate(self, nums, k: int) -> bool:
10+
seen = {}
11+
for i, n in enumerate(nums):
12+
if n in seen and i - seen[n] <= k:
13+
return True
14+
seen[n] = i
15+
return False
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
Problem:
3+
-----------------------------------------------
4+
https://leetcode.com/problems/group-anagrams
5+
6+
7+
HashMap Solution:
8+
-----------------------------------------------
9+
@description:
10+
We can group the anagrams in a hashmap
11+
where we create a key representing their letters sorted.
12+
13+
Actually, designing a key is to build a mapping relationship by yourself
14+
between the original information and the actual key used by hash map.
15+
When you design a key, you need to guarantee that:
16+
1. All values belong to the same group will be mapped in the same group.
17+
2. Values which needed to be separated into different groups will not be mapped into the same group.
18+
19+
This process is similar to design a hash function, but here is an essential difference.
20+
A hash function satisfies the first rule but might not satisfy the second one.
21+
But your mapping function should satisfy both of them.
22+
23+
In the example above, our mapping strategy can be:
24+
sort the string and use the sorted string as the key.
25+
That is to say, both "eat" and "ate" will be mapped to "aet".
26+
27+
Input: strs = ["eat","tea","tan","ate","nat","bat"]
28+
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
29+
30+
["eat","tea","tan","ate","nat","bat"]
31+
32+
key value
33+
["aet"] - ["eat","tea", "ate"]
34+
["ant"] - ["nat","tan"]
35+
["abt"] - ["bat"]
36+
37+
@complexity:
38+
Time: O(n*klogk), where n is the number of anagrams and k is the max_len_anagram out of them
39+
Space: O(n), for the hashmap of all strings with no repetition + the sorted versions of each anagram as keys
40+
"""
41+
class Solution:
42+
def groupAnagrams(self, strs):
43+
if len(strs) == 0:
44+
return [[""]]
45+
46+
hash_map = {}
47+
48+
for s in strs:
49+
key = ''.join(sorted(s))
50+
if key in hash_map:
51+
hash_map.get(key).append(s)
52+
else:
53+
hash_map[key] = [s]
54+
55+
return hash_map.values()
56+

0 commit comments

Comments
 (0)