0
0
Data-structures-theoryHow-ToBeginner ยท 3 min read

Time Complexity of Stack Operations Explained Simply

The time complexity of basic stack operations push, pop, and peek is O(1), meaning they run in constant time. This is because these operations only add, remove, or view the top element without traversing the entire stack.
๐Ÿ“

Syntax

A stack typically supports these operations:

  • push(element): Adds an element to the top of the stack.
  • pop(): Removes and returns the top element.
  • peek(): Returns the top element without removing it.

Each operation works on the top of the stack only.

plaintext
stack.push(element)
stack.pop()
stack.peek()
๐Ÿ’ป

Example

This example shows how push, pop, and peek work on a stack and their constant time behavior.

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

    def push(self, item):
        self.items.append(item)  # O(1)

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

    def peek(self):
        if not self.items:
            return None
        return self.items[-1]  # O(1)

stack = Stack()
stack.push(10)
stack.push(20)
print("Top element after pushes:", stack.peek())
popped = stack.pop()
print("Popped element:", popped)
print("Top element after pop:", stack.peek())
Output
Top element after pushes: 20 Popped element: 20 Top element after pop: 10
โš ๏ธ

Common Pitfalls

One common mistake is assuming stack operations take longer because the stack grows. However, push, pop, and peek always run in constant time O(1) because they only affect the top element.

Another pitfall is confusing stack operations with searching or traversing the stack, which would take O(n) time.

python
wrong:  # Searching for an element in stack
for item in stack.items:
    if item == target:
        return True  # This is O(n), not a basic stack operation

right:  # Using only push/pop/peek
stack.push(5)  # O(1)
stack.pop()    # O(1)
stack.peek()   # O(1)
๐Ÿ“Š

Quick Reference

OperationTime Complexity
pushO(1)
popO(1)
peek (top)O(1)
โœ…

Key Takeaways

Stack operations push, pop, and peek run in constant time O(1).
These operations only affect the top element, so they do not depend on stack size.
Searching or traversing a stack is not a basic stack operation and takes O(n) time.
Understanding time complexity helps write efficient code using stacks.
Always use push/pop/peek for stack manipulation to maintain O(1) performance.