Queue

Peek Front

What is Peek Front Operation?

Peek front (sometimes just called front) lets you look at whatever's sitting at the head of the queue — the next thing due to be dequeued — without actually taking it out. Nothing about the queue changes; you're just reading its current state.

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
Advertisement

Practical Applications

Common use cases for peek:

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

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.

Visualize First-In-First-Out (FIFO) operations in real-time

Test Your Knowledge before moving forward!

Queue Peek Operation Quiz

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 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;
  }
}

Done With the Learning

Mark queue : Peek Front as done and view it on your dashboard

Explore Other Operations