Peek Top Element of Stack in DSA Python - Time & Space 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.
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 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.
Looking at the top element takes the same amount of time no matter how big the stack is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays the same as the stack grows.
Time Complexity: O(1)
This means peeking the top element takes a constant time regardless of stack size.
[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.
Knowing that peek is a constant time operation helps you explain stack efficiency clearly in interviews.
"What if the stack was implemented using a linked list instead of a list? How would the time complexity of peek change?"
Practice
peek operation do in a stack?Solution
Step 1: Understand stack operations
A stack follows Last-In-First-Out (LIFO). The top element is the last added item.Step 2: Define peek operation
Peek returns the top element without removing it, unlike pop which removes it.Final Answer:
Returns the top element without removing it -> Option DQuick Check:
Peek = top element without removal [OK]
- Confusing peek with pop
- Thinking peek adds elements
- Assuming peek returns bottom element
stack?Solution
Step 1: Recall Python list indexing
Python lists use negative indexing;stack[-1]accesses the last element.Step 2: Differentiate peek from pop
stack.pop()removes the element, so it is not peek.stack.peek()andstack.top()are not valid list methods.Final Answer:
stack[-1] -> Option AQuick Check:
Peek = stack[-1] [OK]
- Using pop() which removes element
- Using non-existent peek() or top() methods
- Using positive index 0 instead of -1
stack = [10, 20, 30] print(stack[-1]) stack.append(40) print(stack[-1])
Solution
Step 1: Check initial peek
Initial stack is [10, 20, 30].stack[-1]is 30, so first print outputs 30.Step 2: Append and peek again
After appending 40, stack becomes [10, 20, 30, 40].stack[-1]is now 40, so second print outputs 40.Final Answer:
30 40 -> Option AQuick Check:
Peek before append = 30, after append = 40 [OK]
- Confusing peek with pop output
- Not updating peek after append
- Printing first element instead of last
stack = [5, 15, 25] top = stack.pop[-1] print(top)
Solution
Step 1: Analyze pop usage
popis a method and should be called with parentheses, not square brackets.stack.pop[-1]is invalid syntax.Step 2: Understand correct peek syntax
To peek, usestack[-1]. To pop, usestack.pop(). Mixing them causes error.Final Answer:
pop is used incorrectly with square brackets -> Option BQuick Check:
pop() needs parentheses, not brackets [OK]
- Using pop with brackets instead of parentheses
- Confusing peek with pop
- Assuming pop[-1] is valid syntax
Solution
Step 1: Understand empty stack risk
Accessingstack[-1]when stack is empty causes IndexError.Step 2: Implement safe peek
Check if stack length > 0 before peeking to avoid error.Final Answer:
Check if stack is not empty before peeking -> Option CQuick Check:
Peek safely by checking stack length first [OK]
- Peeking without checking empty stack
- Using pop() which removes element
- Ignoring exceptions from empty stack access
Ready to prove it?
Pass the test and this pattern moves unknown
