Queue - Peek Front

What is Peek Front Operation?

The peek front operation (also called front) retrieves the element at the front of the queue without removing it. This operation allows you to examine the next element to be processed while maintaining the queue's integrity.

How Does It Work?

Peek returns the front element while keeping the queue unchanged.

Example with queue: [A, B, C, D]

  1. Current Queue: [A, B, C, D]
  2. peekFront(): Returns 'A'
  3. Queue After Peek: [A, B, C, D] (unchanged)

Contrast with dequeue() which would remove 'A' from the queue.

Implementation Details

Different implementations handle peek similarly:

  1. Array-based Queue:
    • Return array[front]
    • Check for empty queue first
  2. Linked List Queue:
    • Return head.data
  3. Circular Buffer:
    • Return buffer[front]
    • Handle wrap-around cases

Algorithm Steps

Basic peek operation algorithm:

  1. Check if queue is empty (use isEmpty())
  2. If empty, return error/exception (or null)
  3. Access the data at front position
  4. Return the data without modifying pointers

Time Complexity

Peek operation always runs in O(1) constant time because:

  • Direct access to front element
  • No iteration needed
  • No structural changes to queue

Practical Applications

Common use cases for peek:

  • Previewing next item before processing
  • Priority checking in priority queues
  • Conditional processing logic
  • Debugging queue contents

Error Handling

Important considerations:

  • Always check isEmpty() before peeking
  • Options for empty queue:
    1. Throw exception (e.g., EmptyQueueException)
    2. Return null/undefined
    3. Return special sentinel value
  • Document behavior in your API

The peek front operation is essential for non-destructive queue inspection, enabling more flexible queue processing patterns while maintaining FIFO order. It's particularly valuable in scenarios where decision-making depends on the next item's properties without committing to its removal.

Play with Enqueue, Dequeue, and Peek Front to see a queue in action!

Queue is empty
FrontRear
Queue is empty!

Test Your Knowledge before moving forward!

Queue Quiz Challenge

How it works:

  • +1 point for each correct answer
  • 0 points for wrong answers
  • -0.5 point penalty for viewing explanations
  • Earn stars based on your final score (max 5 stars)

Queue Implementation (Peek Front)

// Queue peek (front) in JavaScript
class Queue {
  constructor() {
    this.items = [];
  }

  // Get front element without removing
  peek() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    return this.items[0];
  }

  // Helper method
  isEmpty() {
    return this.items.length === 0;
  }
}

Explore Other Operations