Challenge - 5 Problems
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of peeking the top element after push operations?
Consider the following Java code using a stack. What will be printed after the peek operation?
DSA Java
import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack.peek()); } }
Attempts:
2 left
💡 Hint
Peek returns the last pushed element without removing it.
✗ Incorrect
The stack pushes 10, then 20, then 30. Peek returns the top element, which is 30.
❓ Predict Output
intermediateWhat happens when peek is called on an empty stack?
What error or output will this Java code produce?
DSA Java
import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); System.out.println(stack.peek()); } }
Attempts:
2 left
💡 Hint
Peek on empty stack throws an exception.
✗ Incorrect
Calling peek on an empty Java Stack throws EmptyStackException.
🔧 Debug
advancedWhy does this peek operation print the wrong value?
Find the bug in this code that causes peek to print 20 instead of 30.
DSA Java
import java.util.Stack; public class Main { public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); stack.pop(); System.out.println(stack.peek()); } }
Attempts:
2 left
💡 Hint
Pop removes the top element before peek.
✗ Incorrect
Pop removes the last pushed element 30, so peek returns the next top element 20.
🧠 Conceptual
advancedWhat is the time complexity of the peek operation on a stack?
Choose the correct time complexity for the peek operation on a stack implemented with an array or linked list.
Attempts:
2 left
💡 Hint
Peek accesses the top element directly without iteration.
✗ Incorrect
Peek returns the top element directly, so it runs in constant time O(1).
🚀 Application
expertAfter a sequence of operations, what is the top element of the stack?
Given the following operations on an empty stack, what will peek return?
DSA Java
Stack<String> stack = new Stack<>(); stack.push("apple"); stack.push("banana"); stack.pop(); stack.push("cherry"); stack.push("date"); stack.pop(); System.out.println(stack.peek());
Attempts:
2 left
💡 Hint
Track each push and pop carefully to find the top element.
✗ Incorrect
Operations leave "cherry" at the top after the last pop removes "date".
