Push Operation on Stack in DSA C - Time & Space Complexity
We want to understand how the time needed to add an item to a stack changes as the stack grows.
How does the push operation behave when the stack size increases?
Analyze the time complexity of the following code snippet.
// Push operation on stack
void push(int stack[], int *top, int value, int max_size) {
if (*top == max_size - 1) {
// Stack overflow
return;
}
(*top)++;
stack[*top] = value;
}
This code adds a new value to the top of the stack if there is space.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single assignment to the stack array at the top position.
- How many times: Exactly once per push call, no loops or recursion involved.
Each push does a fixed number of steps regardless of stack size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 3 steps (check, increment, assign) |
| 100 | 3 steps |
| 1000 | 3 steps |
Pattern observation: The number of steps stays the same no matter how big the stack is.
Time Complexity: O(1)
This means pushing an item takes the same short time no matter how many items are already in the stack.
[X] Wrong: "Push takes longer as the stack grows because it has to move all items."
[OK] Correct: Push only adds one item at the top without moving others, so time does not grow with stack size.
Knowing push is always quick helps you explain why stacks are efficient for adding data, a key skill in many coding problems.
"What if the stack was implemented using a linked list instead of an array? How would the time complexity of push change?"
