Queue Peek Front
Given an array representing a queue, return the element at the front of the queue without removing it. The front is the first element that was added and the next one to be dequeued.
For example, the front of [10, 20, 30] is 10. The front of [5] is 5. If the queue is empty, return 0. The operation does not modify the queue — it only reads the front element.
Peeking at the front element is a fundamental queue operation alongside enqueue and dequeue. It allows you to inspect the next element to be processed without actually removing it, which is useful for conditional processing, priority checks, and look-ahead algorithms.
In array-based queue implementations, the front is at index 0 (assuming no offset). In linked-list-based queues, the front is the head node's value. In circular queues, the front is tracked by a separate front pointer that wraps around when it reaches the end of the array.
Edge cases include an empty queue (return 0), a single-element queue (return that element), and a queue with multiple elements (return the first element). The original queue must remain unchanged after the operation.
Example Input & Output
Algorithm Flow
Solution Approach
Return the front element of the queue (the first element in the array) without removing it. Check if the queue is empty first and return 0 if it is.
The front of a queue is the element that has been waiting the longest and will be dequeued next. Peeking at it allows inspection without modifying the queue, which is essential for algorithms that need to look ahead before processing. In breadth-first search, peeking lets you examine the next node to explore without removing it.
Time O(1), Space O(1).
Best Answers
class Solution {
public int solution(int[] nums) {
return nums.length>0?nums[0]:0;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
