0
0
DSA Pythonprogramming~5 mins

Peek Top Element of Stack in DSA Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Peek Top Element of Stack
O(1)
Understanding Time Complexity

We want to understand how long it takes to look at the top item of 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 push(self, item):
        self.items.append(item)

    def peek(self):
        return self.items[-1] if self.items else None

This code defines a stack and shows how to peek at the top element without removing it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing the last element of the list (stack top).
  • How many times: Exactly once per peek call, no loops or recursion.
How Execution Grows With Input

Looking at the top element takes the same amount of time no matter how big the stack is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The operation count stays the same as the stack grows.

Final Time Complexity

Time Complexity: O(1)

This means peeking the top element takes a constant time regardless of stack size.

Common Mistake

[X] Wrong: "Peeking takes longer if the stack is bigger because it has to look through all elements."

[OK] Correct: Peeking only looks at the last item directly, no need to check other elements.

Interview Connect

Knowing that peek is a 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 peek change?"