Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Design Hashmap
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# I’m using an array of buckets where each bucket is just a list of (key, value) pairs.
# When I insert, I either update an existing key in that bucket or push a new pair if the key isn’t there.
# It’s kind of like rebuilding a tiny version of Python’s dict, and it really forces me to think about collisions and updates carefully.

class MyHashMap:

def __init__(self):
self.size = 1000
self.buckets = [[] for _ in range(self.size)]

def _hash(self, key: int) -> int:
return key % self.size

def put(self, key: int, value: int) -> None:
idx = self._hash(key)
bucket = self.buckets[idx]

for i, (k, v) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return

# If key not found, append new pair
bucket.append((key, value))

def get(self, key: int) -> int:
idx = self._hash(key)
bucket = self.buckets[idx]

for k, v in bucket:
if k == key:
return v
return -1

def remove(self, key: int) -> None:
idx = self._hash(key)
bucket = self.buckets[idx]

for i, (k, v) in enumerate(bucket):
if k == key:
bucket.pop(i)
return
29 changes: 29 additions & 0 deletions implement queue
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# I’m using two stacks because it lets me fake the behavior of a queue even though stacks are LIFO.
# The idea is that I push everything into one stack, and when I need to pop or peek, I dump things into the second stack so the order flips.
# It feels weird at first, but once the second stack has the reversed order, getting the front element becomes super easy.

class MyQueue:

def __init__(self):
self.in_stack = [] # stack for pushing new elements
self.out_stack = [] # stack for popping/peeking in queue order

def push(self, x: int) -> None:
self.in_stack.append(x)

def _shift(self):
# Move elements only when out_stack is empty
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())

def pop(self) -> int:
self._shift()
return self.out_stack.pop()

def peek(self) -> int:
self._shift()
return self.out_stack[-1]

def empty(self) -> bool:
return not self.in_stack and not self.out_stack