0
0
DSA Pythonprogramming~5 mins

Push Operation on Stack in DSA Python - 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 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.

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

This code adds an item to the top of the stack using a list's append method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding one item to the end of the list (stack).
  • How many times: Each push adds exactly one item, no loops or recursion involved.
How Execution Grows With Input

Adding one item takes the same amount of time no matter how many items are already in the stack.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays constant as the stack grows.

Final Time Complexity

Time Complexity: O(1)

This means adding an item to the stack takes the same short time no matter how big the stack is.

Common Mistake

[X] Wrong: "Push takes longer as the stack grows because it has to move all items."

[OK] Correct: The push just adds to the end of the list without moving existing items, so time stays the same.

Interview Connect

Knowing push is very fast helps you explain why stacks are great for quick add/remove tasks in real programs.

Self-Check

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