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
61 changes: 61 additions & 0 deletions DesignHashmap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
''' Time Complexity : Worst case for collision : O(n)
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Your code here along with comments explaining your approach

Approach : Primary staorage as Array of type Node and secondary storage as linkedlist
'''
class ListNode:
def __init__(self,key=None,value=None,next=None):
self.key=key
self.value=value
self.next=next

class MyHashMap:

def __init__(self):
self.bucket=1000
self.storage = [ListNode() for _ in range(self.bucket)]

def put(self, key: int, value: int) -> None:
print("put :",key,value)
index = key % self.bucket
if self.storage[index]:
curr = self.storage[index]
while curr.next:
if curr.next.key == key:
curr.next.value = value
return
curr = curr.next
curr.next = ListNode(key, value)

def get(self, key: int) -> int:
print("get:",key)
index = key % self.bucket
if self.storage[index]:
curr = self.storage[index]
while curr.next:
if curr.next.key == key:
return curr.next.value
curr = curr.next
return -1

def remove(self, key: int) -> None:
print("remove :",key)
index = key % self.bucket
if self.storage[index]:
curr = self.storage[index]
while curr.next:
if curr.next.key == key:
curr.next = curr.next.next
return
curr = curr.next


# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
42 changes: 42 additions & 0 deletions QueueUsingStack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
''' Time Complexity :
push operation - 0(1)
pop, peek : O(1) amortized
Space Complexity : O(n)
Did this code successfully run on Leetcode : Yes
Any problem you faced while coding this : No

Your code here along with comments explaining your approach

Approach : 1. Maintain 2 stack, inStack and minStack, push always in inStack
2. For pop and peek, pop elements from inStack to minStack
'''

class MyQueue:
def __init__(self):
self.in_stack=[]
self.out_stack=[]

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

def pop(self) -> int:
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
return self.out_stack.pop()

def peek(self) -> int:
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
return self.out_stack[-1]

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

# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()