Bird
0
0
DSA Cprogramming~5 mins

Push Operation on Stack in DSA C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Push Operation on Stack
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each push does a fixed number of steps regardless of stack size.

Input Size (n)Approx. Operations
103 steps (check, increment, assign)
1003 steps
10003 steps

Pattern observation: The number of steps stays the same no matter how big the stack is.

Final Time Complexity

Time Complexity: O(1)

This means pushing an item takes the same short time no matter how many items are already in the stack.

Common Mistake

[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.

Interview Connect

Knowing push is always quick helps you explain why stacks are efficient for adding data, a key skill in many coding problems.

Self-Check

"What if the stack was implemented using a linked list instead of an array? How would the time complexity of push change?"