Peek Front Element of Queue in DSA C - Time & Space Complexity
We want to understand how long it takes to look at the front item in a queue.
The question is: How does the time to peek change as the queue grows?
Analyze the time complexity of the following code snippet.
// Peek front element of a queue
int peekFront(Queue* q) {
if (q->front == NULL) {
return -1; // Queue is empty
}
return q->front->data;
}
This code returns the value at the front of the queue without removing it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the front pointer of the queue.
- How many times: Exactly once per peek operation.
Looking at the front element takes the same steps no matter how big the queue is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant even if the queue grows larger.
Time Complexity: O(1)
This means peeking the front element takes the same short time no matter how many items are in the queue.
[X] Wrong: "Peeking the front element takes longer if the queue is bigger because it has to look through all items."
[OK] Correct: The front element is directly accessible via a pointer, so no searching is needed regardless of queue size.
Knowing that peeking is a quick, constant-time operation helps you explain queue efficiency clearly in interviews.
"What if the queue was implemented using an array without a front pointer? How would the time complexity of peeking change?"
