Challenge - 5 Problems
Queue 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 front element in this queue?
Consider the following Java code that uses a queue. What will be printed after peeking the front element?
DSA Java
import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); q.add(10); q.add(20); q.add(30); System.out.println(q.peek()); } }
Attempts:
2 left
💡 Hint
Peek returns the front element without removing it.
✗ Incorrect
The peek() method returns the first element in the queue without removing it. Since 10 was added first, it is at the front.
❓ Predict Output
intermediateWhat happens when peeking an empty queue?
What will be the output of the following Java code?
DSA Java
import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<String> q = new LinkedList<>(); System.out.println(q.peek()); } }
Attempts:
2 left
💡 Hint
Peek returns null if the queue is empty.
✗ Incorrect
The peek() method returns null if the queue is empty instead of throwing an exception.
❓ Predict Output
advancedWhat is the output after multiple peek and poll operations?
Given the following Java code, what will be printed?
DSA Java
import java.util.LinkedList; import java.util.Queue; public class Main { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); q.add(5); q.add(15); q.add(25); System.out.println(q.peek()); q.poll(); System.out.println(q.peek()); q.poll(); System.out.println(q.peek()); } }
Attempts:
2 left
💡 Hint
Peek shows front element; poll removes it.
✗ Incorrect
Initially, peek returns 5. After poll removes 5, peek returns 15. After poll removes 15, peek returns 25.
🔧 Debug
advancedIdentify the error when peeking a queue declared as List
What error will this Java code produce?
DSA Java
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> q = new ArrayList<>(); q.add(1); q.add(2); System.out.println(q.peek()); } }
Attempts:
2 left
💡 Hint
List interface does not have peek() method.
✗ Incorrect
The List interface does not define a peek() method, so the compiler will report cannot find symbol error.
🧠 Conceptual
expertWhich data structure guarantees O(1) peek for front element?
Among these data structures, which one guarantees constant time O(1) peek operation for the front element?
Attempts:
2 left
💡 Hint
Peek means accessing front without removal.
✗ Incorrect
A linked list based queue keeps a reference to the front node, so peek is O(1). ArrayList provides O(1) access by index but does not guarantee front element peek in a queue context. BST and Stack do not provide front element peek in O(1).
