Course contentsShow
← Computer Science
Lesson 593 of 2,87214. Heaps and Priority QueuesFree lesson

Peek Operation for Priority Inspection

Constant-time access to maximum/minimum element without removal from heap.

Peek Operation for Priority Inspection

What you'll learn: How to view the highest (or lowest) priority element in a heap without removing it, in constant time.

The Core Idea

When you have a priority queue backed by a heap, sometimes you want to look at the most important element without actually taking it out. This is called the peek operation. Unlike extract-max/min which removes the root element, peek simply returns the value at the root while leaving the heap structure completely unchanged.

Think of it like checking the top item in a stack of urgent emails without removing it from your inbox. You're just inspecting what's next, not processing it yet.

Why Peek is Useful

Many algorithms need to check the priority of the next item before deciding whether to process it. For example:

  • Event schedulers that check if the next event is due
  • Graph algorithms that need to compare priorities before extraction
  • Simulations that peek at upcoming events to make decisions

The Implementation

Since heaps are stored as arrays with the root at index 0 (or index 1 in 1-indexed implementations), peek is trivially simple:

0-indexed: return heap[0]
1-indexed: return heap[1]

That's it! No bubbling, no comparisons, no restructuring.

Time Complexity

Peek runs in O(1) constant time because:

  • It's a single array access
  • No comparisons with children are needed
  • The heap structure remains unchanged

This contrasts with extract (O(log n)) which must reorganize the heap after removal.

Key Takeaway: The peek operation provides O(1) access to the root element of a heap, allowing you to inspect the highest/lowest priority item without removing it or modifying the heap structure.