0
0
DSA Pythonprogramming~5 mins

Pop Operation on Stack in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Pop Operation on Stack
O(1)
Understanding Time Complexity

We want to understand how long it takes to remove an item from a stack.

Specifically, how the time changes as the stack grows bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

    def pop(self):
        if not self.items:
            return None
        return self.items.pop()

This code removes the top item from the stack if it exists.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Removing the last item from the list.
  • How many times: This happens once per pop call, no loops or recursion inside pop.
How Execution Grows With Input

Removing the top item takes the same steps no matter how big the stack is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays the same even if the stack grows.

Final Time Complexity

Time Complexity: O(1)

This means popping an item takes a fixed amount of time regardless of stack size.

Common Mistake

[X] Wrong: "Pop takes longer if the stack is bigger because it has more items."

[OK] Correct: Pop only removes the last item directly without checking others, so time does not grow with stack size.

Interview Connect

Knowing that pop is a quick, constant-time operation helps you explain stack efficiency clearly in interviews.

Self-Check

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