PriorityQueue<TElement, TPriority> · C#

Peek / TryPeek

Returns the minimum element without removing it.

public TElement Peek(); public bool TryPeek(out TElement element, out TPriority priority)

Complexity

Best caseO(1)
Worst caseO(1)
Extra spaceO(1)

The heap invariant keeps the minimum at index 0.

Tested example

var queue = new PriorityQueue<string, int>();
Assert.False(queue.TryPeek(out _, out _));
queue.Enqueue("only", 9);
Assert.Equal("only", queue.Peek());  // no removal
Assert.Equal(1, queue.Count);
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/PriorityQueueExamples.cs

Behaviour

Returns
The element with the smallest priority.
Errors and preconditions
Peek: InvalidOperationException if empty.
Changes
Nothing.
Memory and invalidation
No allocation.