TheAlgorithms/Java · error · IllegalArgumentException

Frequencies cannot be negative

Error message

Frequencies cannot be negative

What it means

Thrown by OptimalBinarySearchTree.validateInput when any frequency is negative. Frequencies represent access weights/costs and are summed into prefix sums; negative frequencies are meaningless for an OBST cost model. Message: 'Frequencies cannot be negative'.

Source

Thrown at src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java:97

                    }
                }
            }
        }

        return optimalCost[0][nodeCount - 1];
    }

    private static void validateInput(int[] keys, int[] frequencies) {
        if (keys == null || frequencies == null) {
            throw new IllegalArgumentException("Keys and frequencies cannot be null");
        }
        if (keys.length != frequencies.length) {
            throw new IllegalArgumentException("Keys and frequencies must have the same length");
        }

        for (int frequency : frequencies) {
            if (frequency < 0) {
                throw new IllegalArgumentException("Frequencies cannot be negative");
            }
        }
    }

    private static int[][] sortNodes(int[] keys, int[] frequencies) {
        int[][] sortedNodes = new int[keys.length][2];
        for (int index = 0; index < keys.length; index++) {
            sortedNodes[index][0] = keys[index];
            sortedNodes[index][1] = frequencies[index];
        }

        // Sort by key so the nodes can be treated as an in-order BST sequence.
        Arrays.sort(sortedNodes, Comparator.comparingInt(node -> node[0]));

        for (int index = 1; index < sortedNodes.length; index++) {
            if (sortedNodes[index - 1][0] == sortedNodes[index][0]) {
                throw new IllegalArgumentException("Keys must be distinct");
            }

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate every frequency >= 0 at the data boundary.
  2. Replace sentinel/missing markers with 0 or filter the entry out entirely.
  3. Add assertions in the data-ingest layer.

Example fix

// before
int[] freq = {3, -1, 5};

// after
for (int f : freq) {
    if (f < 0) throw new IllegalArgumentException("negative freq: " + f);
}
Defensive patterns

Strategy: validation

Validate before calling

for (int f : frequencies) {
    if (f < 0) throw new IllegalArgumentException("negative frequency: " + f);
}

Prevention

When it happens

Trigger: Passing frequencies containing a negative value; using -1 as a 'missing' marker in frequency data; signed-int parsing of unsigned source data.

Common situations: Aggregating counts where a bug subtracted too much; reading frequencies from a config with a typo'd negative number.

Related errors


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