Challenge - 5 Problems
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output after peeking the top element?
Consider the following stack operations. What will be printed after the peek operation?
DSA Python
stack = [] stack.append(10) stack.append(20) stack.append(30) print(stack[-1])
Attempts:
2 left
💡 Hint
Remember, peek means looking at the last added item without removing it.
✗ Incorrect
The last element added to the stack is 30, so peek returns 30.
❓ Predict Output
intermediate2:00remaining
What happens when peeking an empty stack?
What error will this code produce when trying to peek the top element of an empty stack?
DSA Python
stack = [] print(stack[-1])
Attempts:
2 left
💡 Hint
Think about what happens when you access an index that does not exist.
✗ Incorrect
Accessing stack[-1] on an empty list raises IndexError because there is no element.
🔧 Debug
advanced2:00remaining
Identify the error in this peek function implementation
This function is supposed to return the top element of the stack without removing it. What error will it cause?
DSA Python
def peek(stack): return stack.pop() stack = [1, 2, 3] print(peek(stack)) print(stack)
Attempts:
2 left
💡 Hint
Check what pop() does compared to peek.
✗ Incorrect
pop() removes and returns the top element, so the stack changes. Peek should not remove.
❓ Predict Output
advanced2:00remaining
What is the output after multiple peek operations?
Given the stack operations below, what will be printed?
DSA Python
stack = [] stack.append('a') stack.append('b') print(stack[-1]) stack.pop() print(stack[-1])
Attempts:
2 left
💡 Hint
Peek shows the last element. Pop removes it.
✗ Incorrect
First peek shows 'b', then pop removes 'b', second peek shows 'a'.
🧠 Conceptual
expert2:00remaining
Why is peek operation O(1) time complexity in a stack?
Choose the best explanation for why peeking the top element of a stack is done in constant time.
Attempts:
2 left
💡 Hint
Think about where the top element is stored in a stack implemented with a list.
✗ Incorrect
In a stack implemented with a list, the top element is at the last index, accessible directly in O(1).