Skip to documentation
Data structures / Stack
06 / 18
Our visualization tool supports stack operations through an intuitive graphical interface. When working with stacks, each element is represented as a rectangle, with the value displayed inside. The elements are arranged vertically, with a clear indicator for the top of the stack, making it easy to understand stack operations at a glance.
Let's look at some common stack algorithms and their visualizations:
# @ignore-function-tree
def check_balanced_parentheses(expr: str, stack: Stack) -> bool:
"""Check if expression has balanced parentheses"""
brackets = {')': '(', '}': '{', ']': '['}
for char in expr:
if char in '({[':
stack.push(char)
elif char in ')}]':
if stack.empty() or stack.peek() != brackets[char]:
return False
stack.pop()
return stack.empty()
# Example usage
expr = "{[()]}"
result = check_balanced_parentheses(expr, Stack())
def evaluate_postfix(expr: str, stack: Stack) -> int:
"""
Evaluate postfix expression.
Example: "23+" evaluates to 5
"""
operators = {'+': lambda x,y: x+y,
'-': lambda x,y: x-y,
'*': lambda x,y: x*y,
'/': lambda x,y: x/y}
for char in expr:
if char.isdigit():
stack.push(int(char))
elif char in operators:
b = stack.pop()
a = stack.pop()
stack.push(operators[char](a, b))
return stack.pop()
# Example usage
evaluate_postfix("23+45*+", Stack())
def reverse_string(s: str, stack: Stack) -> str:
"""
Reverse a string using stack.
"""
for char in s:
stack.push(char)
result = []
while not stack.empty():
result.append(stack.pop())
return ''.join(result)
# Example usage
reverse_string("Hello World!", Stack())
def remove_adjacent_duplicates(s: str, stack: Stack) -> str:
"""
Remove adjacent duplicate characters.
"""
for char in s:
if not stack.empty() and stack.peek() == char:
stack.pop()
else:
stack.push(char)
result = []
while not stack.empty():
result.append(stack.pop())
return ''.join(result[::-1])
# Example usage
remove_adjacent_duplicates("abbaca", Stack())
# @ignore-function-tree
def next_greater_element(arr: List[int], stack: Stack) -> List[int]:
"""
Find next greater element for each array element.
"""
result = [-1] * len(arr)
for i in range(len(arr)):
while not stack.empty() and arr[stack.peek()] < arr[i]:
result[stack.pop()] = arr[i]
stack.push(i)
return result
# Example usage
next_greater_element([4, 5, 2, 25], Stack())
# @ignore-function-tree
def stock_span(prices: List[int], stack: Stack) -> List[int]:
"""
Calculate stock span values.
"""
spans = [1] * len(prices)
for i in range(len(prices)):
while not stack.empty() and prices[stack.peek()] <= prices[i]:
stack.pop()
spans[i] = i - stack.peek() if not stack.empty() else i + 1
stack.push(i)
return spans
# Example usage
stock_span([100, 80, 60, 70, 60, 75, 85], Stack())
# @ignore-function-tree
def sort_stack(stack: Stack) -> None:
"""
Sort a stack in ascending order using only stack operations.
"""
temp_stack = Stack()
while not stack.empty():
temp = stack.pop()
while not temp_stack.empty() and temp_stack.peek() > temp:
stack.push(temp_stack.pop())
temp_stack.push(temp)
# Copy back to original stack
while not temp_stack.empty():
stack.push(temp_stack.pop())
# Example usage
stack = Stack()
for x in [3, 1, 4, 1, 5, 9]:
stack.push(x)
sort_stack(stack)
# @ignore-function-tree
def reverse_stack(stack: Stack) -> None:
"""
Reverse a stack using recursion.
"""
def insert_at_bottom(stack: Stack, item: int) -> None:
if stack.empty():
stack.push(item)
return
temp = stack.pop()
insert_at_bottom(stack, item)
stack.push(temp)
if not stack.empty():
temp = stack.pop()
reverse_stack(stack)
insert_at_bottom(stack, temp)
# Example usage
stack = Stack()
for x in [1, 2, 3, 4, 5]:
stack.push(x)
reverse_stack(stack)
# @ignore-function-tree
def find_pattern_132(arr: List[int], stack: Stack) -> bool:
"""
Find if array contains pattern 1-3-2.
Pattern: i < j < k and arr[i] < arr[k] < arr[j]
"""
min_values = [float('inf')] * len(arr)
min_values[0] = arr[0]
for i in range(1, len(arr)):
min_values[i] = min(min_values[i-1], arr[i])
for j in range(len(arr)-1, -1, -1):
if arr[j] <= min_values[j]:
continue
while not stack.empty() and stack.peek() <= min_values[j]:
stack.pop()
if not stack.empty() and stack.peek() < arr[j]:
return True
stack.push(arr[j])
return False
# Example usage
find_pattern_132([3, 1, 4, 2], Stack())
# @ignore-function-tree
def valid_stack_sequence(pushed: List[int], popped: List[int], stack: Stack) -> bool:
"""
Check if sequence could have been generated using stack operations.
"""
j = 0
for x in pushed:
stack.push(x)
while not stack.empty() and j < len(popped) and stack.peek() == popped[j]:
stack.pop()
j += 1
return j == len(popped)
# Example usage
valid_stack_sequence([1,2,3,4,5], [4,5,3,2,1], Stack())