Stack Implementation Using Array in DSA Python - Time & Space Complexity
We want to understand how fast stack operations run when using an array.
How does the time to push or pop change as the stack grows?
Analyze the time complexity of the following code snippet.
class Stack:
def __init__(self, capacity):
self.array = [None] * capacity
self.top = -1
self.capacity = capacity
def push(self, value):
if self.top == self.capacity - 1:
return False # stack full
self.top += 1
self.array[self.top] = value
return True
def pop(self):
if self.top == -1:
return None # stack empty
value = self.array[self.top]
self.top -= 1
return value
This code creates a stack using an array and supports push and pop operations.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single step assignments and index updates in push and pop.
- How many times: Each push or pop runs once per call, no loops inside.
Each push or pop does a fixed number of steps regardless of stack size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 4 steps per push/pop |
| 100 | 4 steps per push/pop |
| 1000 | 4 steps per push/pop |
Pattern observation: The time stays the same no matter how big the stack is.
Time Complexity: O(1)
This means each push or pop takes the same short time no matter how many items are in the stack.
[X] Wrong: "Push or pop takes longer as the stack grows because the array is bigger."
[OK] Correct: The code only changes one position in the array each time, so the size does not affect the time.
Knowing that stack operations run in constant time helps you explain why stacks are efficient for many tasks like undo or expression evaluation.
"What if the array needs to resize dynamically when full? How would the time complexity change?"
Practice
Solution
Step 1: Understand stack behavior
A stack stores elements so that the last element added is the first one removed, called LIFO.Step 2: Role of array in stack
An array helps store elements in order and access the last added element easily for push/pop operations.Final Answer:
To store elements in a last-in, first-out (LIFO) order -> Option DQuick Check:
Stack = LIFO [OK]
- Confusing stack with queue (FIFO)
- Thinking array sorts elements automatically
- Assuming random access is main stack feature
Solution
Step 1: Identify Python data types for stack
An array-like structure for stack is a list, initialized with square brackets [].Step 2: Check each option
stack = [] uses [], which is a list. stack = {} is a dictionary, () is a tuple, null (no data).Final Answer:
stack = [] -> Option AQuick Check:
Empty list = empty stack [OK]
- Using {} which creates a dictionary
- Using () which creates a tuple
- Assigning null instead of a list
stack = [] stack.append(10) stack.append(20) stack.pop() print(stack)
Solution
Step 1: Trace push operations
stack.append(10) adds 10, stack becomes [10]. Then stack.append(20) adds 20, stack becomes [10, 20].Step 2: Trace pop operation
stack.pop() removes last element 20, stack becomes [10].Final Answer:
[10] -> Option CQuick Check:
Pop removes last item, stack left with [10] [OK]
- Thinking pop removes first element
- Confusing append with insert
- Expecting stack to be empty after pop
stack = [] stack.push(5) stack.append(10) print(stack)
Solution
Step 1: Check list methods
Python lists use append() to add elements, not push().Step 2: Identify error
stack.push(5) causes AttributeError because 'push' is not a list method.Final Answer:
'push' method does not exist for list -> Option AQuick Check:
Use append(), not push() for list [OK]
- Using push() instead of append()
- Assuming push() is valid for Python lists
- Ignoring error messages
Solution
Step 1: Understand stack emptiness check
To avoid errors, check if stack has no elements by verifying its length is zero.Step 2: Evaluate options
Check if stack's length is zero usinglen(stack) == 0correctly checks length with len(stack) == 0. Try popping and catch exceptions if stack is empty is valid but less efficient. Check if stack is null checks null which is incorrect. Usestack[0] == nullto check emptiness checks first element which may cause error if empty.Final Answer:
Check if stack's length is zero usinglen(stack) == 0-> Option BQuick Check:
Empty stack means length zero [OK]
- Checking stack is null instead of empty
- Accessing stack[0] without checking length
- Relying only on try-except without condition
Ready to prove it?
Pass the test and this pattern moves unknown
