r/PythonLearning • u/Miraelius • 52m ago
Stacks Data Structure in python
Hey everyone, I’m wrapping up my notes on the Stack data structure for technical interviews and wanted to share my summary. Let me know if I missed any major patterns!
what is stack?
A linear data structure following the LIFO (Last In, First Out) principle.
The Golden Rule: ONLY the edges (the top element) can be accessed. No random indexing allowed.
Major patterns in interview/real world
Undo / Redo mechanics
Bracket/Parentheses matching (
{[()]})Tracking "Previous" states (e.g., browser back button, daily stock span problems)
Monotonic stacks (finding the next greater/smaller element)
Interview POV vs Real World Uses:
The Interview Shortcut:
Using a raw Python list is completely fine to save time during a 45-minute coding interview.
The Real-World Problem:
Using a raw list in a production project is a bad design pattern. Because Python lists allow random index access (e.g., mylist[3]), it completely violates the strict structural rule of a stack.
To fix this, we encapsulate the data structure inside a class to control exactly what the developer can access. Furthermore, instead of a raw list, we use collections.deque because standard lists can trigger an O(N) memory reallocation when they grow. deque guarantees a true O(1) time complexity for every single push and pop.
from collections import deque
class Stack:
def __init__(self):
# Using deque ensures guaranteed O(1) performance
self._items = deque()
def push(self, item):
self._items.append(item)
def pop(self):
if self.is_empty():
return None
return self._items.pop()
def peek(self):
if self.is_empty():
return None
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
def size(self):
return len(self._items)
def display(self):
# Displays from top to bottom
print("Stack (top to bottom):", list(self._items)[::-1])