0
0
DSA Pythonprogramming

Stack Implementation Using Array in DSA Python

Choose your learning style9 modes available
Mental Model
A stack is a collection where you add and remove items only from the top, like a stack of plates.
Analogy: Imagine a stack of plates in your kitchen: you can only add a new plate on top or take the top plate off.
Top
 ↑
[ ] -> [ ] -> [ ] -> null
Bottom
Dry Run Walkthrough
Input: Create an empty stack, then push 10, push 20, pop once, push 30
Goal: Show how the stack changes with each push and pop operation
Step 1: Push 10 onto the stack
Top -> [10] null
Why: We add the first item, so it becomes the top
Step 2: Push 20 onto the stack
Top -> [10, 20] null
Why: New item goes on top, so 20 is now the top
Step 3: Pop the top item (20) from the stack
Top -> [10] null
Why: Remove the top item to get back to previous state
Step 4: Push 30 onto the stack
Top -> [10, 30] null
Why: Add new item on top again
Result:
Top -> [10, 30] null
Annotated Code
DSA Python
class Stack:
    def __init__(self, capacity=10):
        self.capacity = capacity
        self.array = [None] * capacity
        self.top = -1

    def is_empty(self):
        return self.top == -1

    def is_full(self):
        return self.top == self.capacity - 1

    def push(self, value):
        if self.is_full():
            print("Stack Overflow")
            return
        self.top += 1  # move top up to next free slot
        self.array[self.top] = value  # place value at top

    def pop(self):
        if self.is_empty():
            print("Stack Underflow")
            return None
        value = self.array[self.top]  # get top value
        self.array[self.top] = None  # clear top slot
        self.top -= 1  # move top down
        return value

    def __str__(self):
        if self.is_empty():
            return "Stack is empty"
        return "Top -> [" + ", ".join(str(self.array[i]) for i in range(self.top + 1)) + "] null"

# Driver code
stack = Stack()
stack.push(10)
stack.push(20)
print(stack)
popped = stack.pop()
print(f"Popped: {popped}")
stack.push(30)
print(stack)
self.top += 1 # move top up to next free slot
advance top pointer to next position for new item
self.array[self.top] = value # place value at top
store new value at the top position
value = self.array[self.top] # get top value
retrieve value from current top before removal
self.array[self.top] = None # clear top slot
clear the slot to avoid stale data
self.top -= 1 # move top down
move top pointer down after removal
OutputSuccess
Top -> [10, 20] null Popped: 20 Top -> [10, 30] null
Complexity Analysis
Time: O(1) for push and pop because we add or remove only at the top without traversing
Space: O(n) where n is capacity because we allocate fixed array space upfront
vs Alternative: Compared to linked list stack, array stack uses fixed space but faster access; linked list uses dynamic space but more memory per element
Edge Cases
Push when stack is full
Prints 'Stack Overflow' and does not add new item
DSA Python
if self.is_full():
Pop when stack is empty
Prints 'Stack Underflow' and returns None
DSA Python
if self.is_empty():
Pop until empty then push again
Stack correctly empties and accepts new pushes
DSA Python
self.top -= 1  # move top down
When to Use This Pattern
When you need last-in-first-out order with fast access, use stack with array for simple fixed-size storage.
Common Mistakes
Mistake: Incrementing top pointer after placing value instead of before
Fix: Increment top before placing value to avoid overwriting
Mistake: Not checking for stack overflow before push
Fix: Always check is_full() before pushing new item
Mistake: Not checking for stack underflow before pop
Fix: Always check is_empty() before popping
Summary
Implements a stack using a fixed-size array with push and pop at the top.
Use when you want simple, fast last-in-first-out storage with known maximum size.
The top pointer moves up on push and down on pop to track the current stack top.