TheAlgorithms/C-Sharp · error · ArgumentException
not in heap!
Error message
{element} not in heap! What it means
BinaryHeap.Remove(element) throws ArgumentException with "{element} not in heap!" when IndexOf(element) returns -1, i.e. the value is not present (which includes an empty heap). The library refuses to remove absent items.
Solutions
- Check heap.Contains(element) (Count > 0 and IndexOf != -1) before Remove().
- Catch ArgumentException around Remove() if absence is expected.
- Verify the element's Equals semantics match what was pushed (especially with custom comparers).
Example fix
// before
heap.Remove(item);
// after
if (heap.Count > 0 && heap.Contains(item))
{
heap.Remove(item);
} Defensive patterns
Strategy: validation
Validate before calling
if (heap.Count > 0 && heap.Contains(element)) heap.Remove(element);
Try / catch
try { heap.Remove(element); } catch (ArgumentException) { /* element absent; ignore or log */ } Prevention
- Check Contains before Remove
- Avoid removing the same element twice
- Be careful with custom comparers and element equality
When it happens
Trigger: Calling Remove() with a value never pushed, a value already removed, or on an empty heap (Index -1).
Common situations: Removing an item twice, removing a struct/equality-mismatched value, or removing from a heap built with a custom comparer where equality assumptions differ.
Understand the failure class
Background: "Not found" and "does not exist" errors: why "Task not found", "No such folder", and "Can't find" fire when a lookup comes back empty — this error's family across 14 libraries.
Related errors
- Heap is empty!
- x is not from the heap
- Heap is empty
- Current value is not present in this heap.
- New value is not than old value.
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/710f6bc969955423.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/Heap/BinaryHeap.cs:154
public bool Contains(T element) => data.Contains(element);
/// <summary>
/// Remove an element from the heap.
/// </summary>
/// <remarks>
/// In removing an element from anywhere in the heap, we only need to push down or up
/// the replacement value depending on how the removed value compares to its
/// replacement value.
/// </remarks>
/// <param name="element">The element to remove from the heap.</param>
/// <exception cref="ArgumentException">Thrown if element is not in heap.</exception>
public void Remove(T element)
{
var idx = data.IndexOf(element);
if (idx == -1)
{
throw new ArgumentException($"{element} not in heap!");
}
Swap(idx, data.Count - 1);
var tmp = data[^1];
data.RemoveAt(data.Count - 1);
if (idx < data.Count)
{
if (comparer.Compare(tmp, data[idx]) > 0)
{
HeapifyDown(idx);
}
else
{
HeapifyUp(idx);
}
}
}View on GitHub (pinned to 96e2905cab)