TheAlgorithms/Java · error · IllegalArgumentException
Edge vertex out of range
Error message
Edge vertex out of range
What it means
Thrown by `checkEdgeVertices` during Graph construction when any edge's `src` or `dest` is negative or `>= vertex`. Every edge endpoint must index a real vertex in `[0, vertex)`. This catches malformed or off-by-one edge definitions before they corrupt the MST computation.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java:214
static List<Edge> boruvkaMST(final Graph graph) {
var boruvkaState = new BoruvkaState(graph);
while (boruvkaState.hasMoreEdgesToAdd()) {
final var cheapest = boruvkaState.computeCheapestEdges();
boruvkaState.merge(cheapest);
}
return boruvkaState.result;
}
/**
* Checks if the edge vertices are in a valid range
*
* @param vertex the vertex to check
* @param upperBound the upper bound for the vertex range
*/
private static void checkEdgeVertices(final int vertex, final int upperBound) {
if (vertex < 0 || vertex >= upperBound) {
throw new IllegalArgumentException("Edge vertex out of range");
}
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Make vertex indices 0-based and ensure all src/dest are in [0, vertex)
- If your data is 1-based, subtract 1 from every endpoint before building Edges
- Set `vertex` to at least `max(src,dest)+1` across all edges
Example fix
// before (1-based data passed directly) edges.add(new Edge(1, vertex, w)); // after (convert 1-based to 0-based) edges.add(new Edge(src - 1, dest - 1, w));
Defensive patterns
Strategy: validation
Validate before calling
for (Edge e : edges) {
if (e.src < 0 || e.src >= vertex || e.dest < 0 || e.dest >= vertex) {
throw new IllegalArgumentException("bad edge " + e.src + "-" + e.dest);
}
} Try / catch
try {
new BoruvkaAlgorithm.Graph(v, edges);
} catch (IllegalArgumentException e) {
// log the offending edge
} Prevention
- Normalize external edge data to 0-based at the boundary
- Derive the vertex count from the maximum referenced endpoint, do not guess it
When it happens
Trigger: An Edge whose `src`/`dest` equals `vertex` (1-based index passed to a 0-based graph), is negative, or references a vertex that does not exist because the vertex count was set too low.
Common situations: Mixing 1-based file data with the 0-based API; vertex count smaller than the max referenced vertex; an edge list built for a larger graph but a smaller `vertex` passed.
Related errors
- Source vertex is out of bounds.
- Vertex {vertex} is out of bounds
- Number of vertices must be positive
- Edges list must not be null or empty
- Incorrect source
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/9798d55ce489d86b.
Report an issue: GitHub.