TheAlgorithms/Java · error · IndexOutOfBoundsException
Invalid column indices
Error message
Invalid column indices
What it means
Thrown by PrefixSum2D.sumRegion(row1, col1, row2, col2) when the column indices are invalid: col1 < 0, col2 >= number of columns, or col2 < col1. Checked only after row indices pass. Bounds are 0-based inclusive against the original matrix column count.
Source
Thrown at src/main/java/com/thealgorithms/prefixsum/PrefixSum2D.java:59
}
/**
* Calculates the sum of the sub-matrix defined by (row1, col1) to (row2, col2).
* Indices are 0-based.
*
* @param row1 Top row index.
* @param col1 Left column index.
* @param row2 Bottom row index.
* @param col2 Right column index.
* @return The sum of the sub-matrix.
* @throws IndexOutOfBoundsException if indices are invalid.
*/
public long sumRegion(int row1, int col1, int row2, int col2) {
if (row1 < 0 || row2 >= prefixSums.length - 1 || row2 < row1) {
throw new IndexOutOfBoundsException("Invalid row indices");
}
if (col1 < 0 || col2 >= prefixSums[0].length - 1 || col2 < col1) {
throw new IndexOutOfBoundsException("Invalid column indices");
}
return prefixSums[row2 + 1][col2 + 1] - prefixSums[row1][col2 + 1] - prefixSums[row2 + 1][col1] + prefixSums[row1][col1];
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Use inclusive 0-based indices: col2 should be lastColIndex (cols-1).
- Normalize corners so col2 >= col1 (swap if inverted).
- Convert 1-based external coordinates to 0-based before calling.
Example fix
// before long s = ps2.sumRegion(r1, c1, r2, c2); // c2 may equal column count // after long s = ps2.sumRegion(r1, c1, r2, Math.min(c2, cols - 1));
Defensive patterns
Strategy: validation
Validate before calling
int cols = matrix[0].length;
if (col1 < 0 || col2 >= cols || col2 < col1) {
throw new IndexOutOfBoundsException("invalid column range");
}
long s = ps2.sumRegion(row1, col1, row2, col2); Type guard
static boolean validColRange(int c1, int c2Inclusive, int cols) {
return c1 >= 0 && c2Inclusive < cols && c2Inclusive >= c1;
} Try / catch
try {
long s = ps2.sumRegion(r1, c1, r2, c2);
} catch (IndexOutOfBoundsException e) {
logger.warn("Bad column range [{}, {}]", c1, c2);
} Prevention
- Use last column index (cols-1), never column count, as the right bound.
- Normalize inverted width corners before calling.
- Convert 1-based coordinates to 0-based at the boundary.
When it happens
Trigger: Call sumRegion(0, -1, 2, 2), sumRegion(0, 0, 2, cols) (col2 past last column), or sumRegion(0, 3, 2, 1) (col2 < col1).
Common situations: Passing column count as right index (cols instead of cols-1); inverted width bounds; 1-based columns not converted.
Related errors
- Invalid row indices
- Invalid range indices
- Invalid range: [%d, %d] for array of size %d
- Input matrix cannot be null or empty
- Invalid range indices
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/0b44ffc912cdfa2f.
Report an issue: GitHub.