-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathHashSet.py
More file actions
42 lines (35 loc) · 1.61 KB
/
HashSet.py
File metadata and controls
42 lines (35 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Time Complexity : O(1)
# Space Complexity : O(n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : two level bucket structure (primary -> secondary) with boolean arrays for constant time access.
class MyHashSet:
def __init__(self):
self.primaryBucketSize = 1000
self.secondaryBucketSize = 1000
self.storage = [[] for _ in range(self.primaryBucketSize)]
def getPrimaryHash(self, key: int) -> int:
return key % self.primaryBucketSize
def getSecondaryHash(self, key: int) -> int:
return key // self.secondaryBucketSize
def add(self, key: int) -> None:
primaryHash = self.getPrimaryHash(key)
if self.storage[primaryHash] == []:
if primaryHash == 0:
self.storage[primaryHash] = [False] * (self.secondaryBucketSize + 1) # handle division edge case for 10^6
else:
self.storage[primaryHash] = [False] * (self.secondaryBucketSize)
secondaryHash = self.getSecondaryHash(key)
self.storage[primaryHash][secondaryHash] = True
def remove(self, key: int) -> None:
primaryHash = self.getPrimaryHash(key)
if self.storage[primaryHash] == []:
return
secondaryHash = self.getSecondaryHash(key)
self.storage[primaryHash][secondaryHash] = False
def contains(self, key: int) -> bool:
primaryHash = self.getPrimaryHash(key)
if not self.storage[primaryHash]:
return False
secondaryHash = self.getSecondaryHash(key)
return self.storage[primaryHash][secondaryHash]