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
34 changes: 34 additions & 0 deletions Queue_using_stacks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Time Complexity : 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
#I have used two stacks to push all the elements to stack2 when peek method is called and return the top element.
#Pop() calls peek() first and then returns top element from stack2.


class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []

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

def peek(self) -> int:
if self.stack2 == []:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]


def pop(self) -> int:
self.peek()
return self.stack2.pop()

def empty(self) -> bool:
if not self.stack1 and not self.stack2:
return True
return False
67 changes: 67 additions & 0 deletions implement_HashMap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Time Complexity : O(1)
// Space Complexity : O(1)
// 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 in three sentences only
#I have designed HashMap using LinkedList that is linear chaining.

class MyHashMap:

class Node:

def __init__(self, key, value):
self.key = key
self.value = value
self.next = None

def __init__(self):
self.data = 1000
self.storage = [None] * self.data

def hash1(self, key):
index = key % self.data
return index

def findPrev(self, head, key):
currentNode = head
prev = None
while currentNode != None and currentNode.key != key:
prev = currentNode
currentNode = currentNode.next
return prev

def put(self, key:int, value:int) -> None:
data_index = self.hash1(key)
if self.storage[data_index] is None:
self.storage[data_index] = self.Node(-1,-1)
prev = self.findPrev(self.storage[data_index], key)
if prev.next is None:
prev.next = self.Node(key, value)
else:
prev.next.value = value


def remove(self, key:int) -> None:
data_index = self.hash1(key)
if self.storage[data_index] is None:
return
prev = self.findPrev(self.storage[data_index], key)
if prev.next == None:
return
temp = prev.next
prev.next = prev.next.next
temp.next = None

def get(self, key:int) -> int:
data_index = self.hash1(key)
if self.storage[data_index] is None:
return -1
prev = self.findPrev(self.storage[data_index], key)
if prev.next == None:
return -1
return prev.next.value