Skip to content

Commit d83e014

Browse files
committed
[feature] add hashmap category
1 parent ca26a64 commit d83e014

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ A catalogue of data structures implementation + algorithms and coding problems a
9494
- [Single cycle check](graphs/single_cycle_check.md)
9595
- [Youngest common ancestor](graphs/youngest_common_ancestor.md)
9696

97+
## Hashmaps
98+
99+
- [Hashmap implementation](hash-maps/hash_map.md)
100+
97101
## Heaps
98102

99103
- [Given buildings, model a skyline](heaps/max_heap_skyline.md)

hash-maps/hash_map.md

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
```python
2+
class HashMap:
3+
def __init__(self, size):
4+
self.size = size
5+
self.hash_table = self.createBuckets()
6+
7+
def createBuckets(self):
8+
return [[] for i in range(self.size)]
9+
10+
def set(self, key, value):
11+
# get bucket hash
12+
bucket_hash = hash(key) % self.size
13+
bucket = self.hash_table[bucket_hash]
14+
15+
found_key = False
16+
for idx, record in enumerate(bucket):
17+
record_key, record_val = record
18+
if record_key == key:
19+
found_key = True
20+
break
21+
if found_key:
22+
bucket[idx] = (key, value)
23+
else:
24+
bucket.append((key, value))
25+
26+
def get(self, key):
27+
# Get the index of the bucket holding the key using the hash function
28+
index = hash(key) % self.size
29+
30+
# get the bucket using the index
31+
bucket = self.hash_table[index]
32+
33+
found_key = False
34+
for idx, record in enumerate(bucket):
35+
record_key, record_val = record
36+
if key == record_key:
37+
found_key = True
38+
break
39+
return record_val if found_key else None
40+
41+
def delete(self, key):
42+
bucket_hash = hash(key) % self.size
43+
found_key = False
44+
for idx, record in enumerate(self.hash_table[bucket_hash]):
45+
record_key, record_value = record
46+
if key == record_key:
47+
found_key = True
48+
break
49+
if found_key:
50+
# delete
51+
self.hash_table.pop(idx)
52+
else:
53+
return f"Key '{key}' does not exist"
54+
55+
56+
```
57+
58+
59+
```python
60+
hashmap = HashMap(10)
61+
```
62+
63+
64+
```python
65+
hashmap.set("something", "soweto")
66+
for i in range(5):
67+
hashmap.set(f"{i}", i)
68+
```
69+
70+
71+
```python
72+
hashmap.get("something")
73+
74+
```
75+
76+
77+
78+
79+
'soweto'
80+
81+
82+
83+
84+
```python
85+
86+
```

0 commit comments

Comments
 (0)