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
- Validate every frequency >= 0 at the data boundary.
- Replace sentinel/missing markers with 0 or filter the entry out entirely.
- 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
- Never use negative numbers as frequency sentinels.
- Validate at the ingest boundary.
- Log the offending index when a negative is found.
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
- Input array should not contain negative number(s).
- Keys and frequencies cannot be null
- Keys and frequencies must have the same length
- Price array cannot be null or empty.
- Rod length cannot be negative.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/81c65d89a92582b4.
Report an issue: GitHub.