Description

A stack, is a data structure which acts like a lego tower. You are unable to take things off the bottom so you must take them off the top. This is called last in first out LIFO.
?

Reach for when

Runtime

push O(1)
pop O(1)

Visualization

LIFO Stack-1783976431147.webp232

Pseudocode

stack = []
for item in items:
	if conditionMet(item):
		put item on stack
	else:
		if isValidRemoval(item):
			pop
		else:
			Error

Code

def is_valid_parentheses(s):
	pairs = {")": "(", "]": "[", "}": "{"}
	stack = []
	for char in s:
		if char not in pairs:
			stack.append(char)
		else:
			if stack and stack[-1] == pairs[char]:
				stack.pop()
			else:
				return False
	return not stack