TheAlgorithms/Java · error · IllegalArgumentException

Array is empty

Error message

Array is empty

What it means

Thrown by SaddlebackSearch.find(int[][], int, int, int) when arr.length == 0. Saddleback search operates on a 2D sorted matrix and needs at least one row to begin. An empty outer array means there is no matrix to search, so the method rejects it.

Source

Thrown at src/main/java/com/thealgorithms/searches/SaddlebackSearch.java:34

 */
public final class SaddlebackSearch {
    private SaddlebackSearch() {
    }

    /**
     * This method performs Saddleback Search
     *
     * @param arr The **Sorted** array in which we will search the element.
     * @param row the current row.
     * @param col the current column.
     * @param key the element that we want to search for.
     * @throws IllegalArgumentException if the array is empty.
     * @return The index(row and column) of the element if found. Else returns
     * -1 -1.
     */
    static int[] find(int[][] arr, int row, int col, int key) {
        if (arr.length == 0) {
            throw new IllegalArgumentException("Array is empty");
        }

        // array to store the answer row and column
        int[] ans = {-1, -1};
        if (row < 0 || col >= arr[row].length) {
            return ans;
        }
        if (arr[row][col] == key) {
            ans[0] = row;
            ans[1] = col;
            return ans;
        } // if the current element is greater than the given element then we move up
        else if (arr[row][col] > key) {
            return find(arr, row - 1, col, key);
        }
        // else we move right
        return find(arr, row, col + 1, key);
    }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check arr.length > 0 before calling find() and return a not-found result {-1, -1} directly.
  2. Validate the matrix at construction/loading time and reject empty inputs upstream.
  3. Use a wrapper that normalizes null/empty matrices to a documented not-found result.

Example fix

// before
int[] pos = SaddlebackSearch.find(matrix, 0, cols - 1, key);

// after
int[] pos = matrix.length == 0 ? new int[]{-1, -1} : SaddlebackSearch.find(matrix, 0, cols - 1, key);
Defensive patterns

Strategy: validation

Validate before calling

if (arr == null || arr.length == 0) return new int[]{-1, -1};

Type guard

public static boolean isNonEmptyMatrix(int[][] m) { return m != null && m.length > 0; }

Prevention

When it happens

Trigger: Calling find(new int[0][], ...); passing a matrix built from an empty row set; deserializing a matrix that came back with zero rows.

Common situations: Matrix loaded from a CSV/file that was empty; downstream computation produced no rows; defaulting to an empty matrix instead of null.

Related errors


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