TheAlgorithms/Java · error · IllegalArgumentException

k must be >= 1

Error message

k must be >= 1

What it means

YensKShortestPaths.kShortestPaths requires k >= 1 because it always computes at least the single shortest path first, then iterates k-1 more times for additional paths. k <= 0 makes no semantic sense (you must return at least one path) and would skip the initial Dijkstra call.

Source

Thrown at src/main/java/com/thealgorithms/graph/YensKShortestPaths.java:132

            throw new IllegalArgumentException("Weights matrix must not be null or empty");
        }
        int n = weights.length;
        for (int i = 0; i < n; i++) {
            if (weights[i] == null || weights[i].length != n) {
                throw new IllegalArgumentException("Weights matrix must be square");
            }
            for (int j = 0; j < n; j++) {
                int val = weights[i][j];
                if (val < NO_EDGE) {
                    throw new IllegalArgumentException("Weights must be -1 (no edge) or >= 0");
                }
            }
        }
        if (src < 0 || dst < 0 || src >= n || dst >= n) {
            throw new IllegalArgumentException("Invalid src/dst indices");
        }
        if (k < 1) {
            throw new IllegalArgumentException("k must be >= 1");
        }
    }

    private static boolean startsWith(List<Integer> list, List<Integer> prefix) {
        if (prefix.size() > list.size()) {
            return false;
        }
        for (int i = 0; i < prefix.size(); i++) {
            if (!Objects.equals(list.get(i), prefix.get(i))) {
                return false;
            }
        }
        return true;
    }

    private static int[][] cloneMatrix(int[][] a) {
        int n = a.length;
        int[][] b = new int[n][n];

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Clamp k to at least 1 before calling: k = Math.max(1, requestedK).
  2. Validate upstream: if the user requested 0 paths, return an empty list without invoking the algorithm.
  3. Default k to 1 when the parameter is optional/unset.

Example fix

// before
int k = request.getCount(); // may be 0
List<List<Integer>> paths = YensKShortestPaths.kShortestPaths(w, s, d, k);

// after
int k = Math.max(1, request.getCount());
List<List<Integer>> paths = YensKShortestPaths.kShortestPaths(w, s, d, k);
Defensive patterns

Strategy: validation

Validate before calling

int safeK = Math.max(1, k);
YensKShortestPaths.kShortestPaths(weights, src, dst, safeK);

Prevention

When it happens

Trigger: Calling with k=0, k negative, or a k value derived from user input that was not validated (e.g. a 'top-N paths' request where N=0).

Common situations: User-facing 'show top K results' feature where K defaults to 0 when unset, a CLI flag parsed as 0, or passing a list size as k when the list is empty.

Related errors


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