1. Implement Queue using Stacks (Leetcode Number: 232)
Create two lists instack and outstack, instack stores the input elements and outstack takes all the elements moved from instack, however the order of those elements is reversed to achieve the function of STACK.
class MyQueue:
MyQueue = []
def __init__(self):
# Initialize the data structure
self.instack = []
self.outstack = []
def push(self, x: int) -> None:
# Attach the element x to the end of the list
self.instack.append(x)
def pop(self) -> int:
# Remove the element from the front of the queue and returns it
if self.empty():
return False
# Return the last element, which is the first element of self.instack
elif self.outstack:
return self.outstack.pop()
# Move the elements from self.instack to self.outstack, starts from self.instack[n - 1] to self.instack[0]. The order of those elements in self.outstack is reversed.
else:
for i in range(len(self.instack)):
self.outstack.append(self.instack.pop())
return self.outstack.pop()
def peek(self) -> int:
# Return the first element of the list, take the value out then append it back to the list
ret_val = self.pop()
self.outstack.append(ret_val)
return ret_val
def empty(self) -> bool:
# Return true if the queue is empty, false otherwise
return not (self.instack or self.outstack)
2. Implement Stack using Queues (Leetcode Number: 225)
Similar to Q1. But the datatype of self.stack is deque as popleft() would be used here.
class MyStack:
def __init__(self):
self.stack = deque()
def push(self, x: int) -> None:
self.stack.append(x)
def pop(self) -> int:
if not self.stack:
return False
else:
for i in range(len(self.stack) - 1):
self.stack.append(self.stack.popleft())
return self.stack.popleft()
def top(self) -> int:
if not self.stack:
return False
else:
return self.stack[-1]
def empty(self) -> bool:
return not self.stack
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
3. Valid Parentheses (Leetcode Number: 225)
Create a stack that is used to store respective close bracket while detecting an open bracket in the string -> When there is an close bracket, check if it's same with the last element in the stack, return false if it doesn't match as all the bracket must come in the right order -> The stack should be empty after going through the whole string, otherwise return false.
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
ver_stack = []
for i in range(len(s)):
if s[i] == "(":
ver_stack.append(")")
elif s[i] == "[":
ver_stack.append("]")
elif s[i] == "{":
ver_stack.append("}")
elif not ver_stack or ver_stack[-1] != s[i]:
return False
else:
ver_stack.pop()
return True if not ver_stack else False
4. Remove All Adjacent Duplicates In String (Leetcode Number: 1047)
Own Stack Solution - Add letter extracted from the string to the stack if the last element in the stack is not a duplicate. Otherwise remove the last element in the stack.
class Solution:
def removeDuplicates(self, s: str) -> str:
stack = []
for letter in s:
if not stack:
stack.append(letter)
elif letter != stack[-1]:
stack.append(letter)
else:
stack.pop()
return "".join(stack)
Template Stack Solution
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list()
for item in s:
if res and res[-1] == item:
res.pop()
else:
res.append(item)
return "".join(res)