TheAlgorithms/Java · error · IllegalStateException

MinPriorityQueue is full. Cannot insert new element.

Error message

MinPriorityQueue is full. Cannot insert new element.

What it means

Thrown by MinPriorityQueue.insert(int) when isFull() returns true. MinPriorityQueue is backed by a fixed-size int[] of length capacity+1, so insert at size+1 would overflow the array. The library enforces its bounded contract at insertion time.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java:46

    /**
     * Initializes a new MinPriorityQueue with a specified capacity.
     *
     * @param c the maximum number of elements the queue can hold
     */
    public MinPriorityQueue(int c) {
        this.capacity = c;
        this.size = 0;
        this.heap = new int[c + 1];
    }

    /**
     * Inserts a new key into the min-priority queue.
     *
     * @param key the value to be inserted
     */
    public void insert(int key) {
        if (this.isFull()) {
            throw new IllegalStateException("MinPriorityQueue is full. Cannot insert new element.");
        }
        this.heap[this.size + 1] = key;
        int k = this.size + 1;
        while (k > 1) {
            if (this.heap[k] < this.heap[k / 2]) {
                int temp = this.heap[k];
                this.heap[k] = this.heap[k / 2];
                this.heap[k / 2] = temp;
            }
            k = k / 2;
        }
        this.size++;
    }

    /**
     * Retrieves the highest priority value (the minimum) without removing it.
     *
     * @return the minimum value in the queue

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check isFull() before insert and drain the queue if full.
  2. Size the queue generously at construction to match expected input volume.
  3. Catch IllegalStateException around insert and grow by creating a larger queue and copying.
  4. Drain the queue with delete() in the producer loop before inserting when full.

Example fix

// before
pq.insert(key); // throws when full

// after
if (pq.isFull()) {
    int min = pq.delete(); // make room
}
pq.insert(key);
Defensive patterns

Strategy: validation

Validate before calling

if (!pq.isFull()) {
    pq.insert(key);
} else {
    // drain or expand capacity
}

Try / catch

try {
    pq.insert(key);
} catch (IllegalStateException e) {
    // queue full — backpressure or grow
}

Prevention

When it happens

Trigger: Inserting more than `capacity` keys into the queue constructed with `new MinPriorityQueue(capacity)`. Inserting in a tight loop without checking isFull.

Common situations: Underestimating the required capacity at construction. Feeding an unbounded input stream into a bounded queue. Reusing a queue without draining it first.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/16e12f746c045931. Report an issue: GitHub.