TheAlgorithms/Java · error · IllegalArgumentException
Invalid node in edge: [{}, {}]
Error message
Invalid node in edge: [{}, {}] What it means
Thrown by CentroidDecomposition.buildFromEdges when an edge references a node id outside [0, n). The builder indexes adj.get(u) and adj.get(v), so an out-of-range endpoint would throw IndexOutOfBoundsException. The IllegalArgumentException reports both offending endpoints.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java:208
}
if (edges.length != n - 1) {
throw new IllegalArgumentException("Tree must have exactly n-1 edges");
}
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int[] edge : edges) {
if (edge.length != 2) {
throw new IllegalArgumentException("Each edge must have exactly 2 nodes");
}
int u = edge[0];
int v = edge[1];
if (u < 0 || u >= n || v < 0 || v >= n) {
throw new IllegalArgumentException("Invalid node in edge: [" + u + ", " + v + "]");
}
adj.get(u).add(v);
adj.get(v).add(u);
}
return new CentroidTree(adj);
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Convert 1-based external ids to 0-based by subtracting 1 before building edges.
- Set n to max(edge ids) + 1 (after conversion) so all endpoints are in range.
- Validate every endpoint against [0, n-1] at the input boundary.
- Reject self-loops and duplicate edges which often accompany id bugs.
Example fix
// before
CentroidTree ct = CentroidDecomposition.buildFromEdges(n, edges);
// after
for (int[] e : edges) {
if (e[0] < 0 || e[0] >= n || e[1] < 0 || e[1] >= n) {
throw new IllegalArgumentException("edge out of range: " + Arrays.toString(e));
}
}
CentroidTree ct = CentroidDecomposition.buildFromEdges(n, edges); Defensive patterns
Strategy: validation
Validate before calling
for (int[] e : edges) {
if (e[0] < 0 || e[0] >= n || e[1] < 0 || e[1] >= n) {
throw new IllegalArgumentException("edge endpoint out of range: " + Arrays.toString(e));
}
} Prevention
- Convert 1-based ids to 0-based before building edges.
- Set n = maxId + 1 to cover all endpoints.
- Validate endpoint ranges at the input boundary.
When it happens
Trigger: Passing edges with 1-based node ids into a 0-based builder. Passing an edge [u, n] where n equals the node count (valid range is 0..n-1). Negative ids from sentinel/uninitialized values.
Common situations: Indexing-convention mismatch between input data (often 1-based) and the algorithm (0-based). Node count n set too low relative to the actual max id in edges. Edges built from a different vertex labeling than expected.
Related errors
- Invalid node: {}
- Number of nodes must be positive
- Tree must have exactly n-1 edges
- Each edge must have exactly 2 nodes
- Tree cannot be empty or null
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/0ef1e199d9262906.
Report an issue: GitHub.