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 = stack.pop() if stack else '#'
if mapping[char] != top:
return False
else:
stack.append(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 == '(':
stack.append(i)
elif c == ')':
if stack:
stack.pop()
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):
self.q.append(x)
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self):
return self.q.popleft()
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 = stack.pop()
res[idx] = i - idx
stack.append(i)
return res
# Test
print(dailyTemperatures([73,74,75,71,69,72,76,73])) # Output: [1,1,4,2,1,1,0,0]