25 Advanced Python Stack Interview Questions with Solutions
1. Valid Parentheses
def isValid(s):
stack = []
mapping = {')':'(', ']':'[', '}':'{'}
for char in s:
if char in mapping:
top = [Link]() if stack else '#'
if mapping[char] != top:
return False
else:
[Link](char)
return not stack
2. Min Remove to Make Valid Parentheses
def minRemoveToMakeValid(s):
stack = []
s = list(s)
for i, c in enumerate(s):
if c == '(':
[Link](i)
elif c == ')':
if stack:
[Link]()
else:
s[i] = ''
for i in stack:
s[i] = ''
return ''.join(s)
3. Implement Stack using Queues
from collections import deque
class MyStack:
def __init__(self):
self.q = deque()
def push(self, x):
[Link](x)
for _ in range(len(self.q) - 1):
[Link]([Link]())
def pop(self):
return [Link]()
def top(self):
return self.q[0]
def empty(self):
return not self.q
4. Daily Temperatures
def dailyTemperatures(temperatures):
stack = []
res = [0] * len(temperatures)
for i, temp in enumerate(temperatures):
while stack and temperatures[stack[-1]] < temp:
idx = [Link]()
res[idx] = i - idx
[Link](i)
return res
# Test
print(dailyTemperatures([73,74,75,71,69,72,76,73])) # Output: [1,1,4,2,1,1,0,0]