TheAlgorithms/Java · error · IllegalArgumentException

Keys and frequencies must have the same length

Error message

Keys and frequencies must have the same length

What it means

Thrown by OptimalBinarySearchTree.validateInput when keys.length != frequencies.length. Each key must be paired with exactly one frequency; mismatched lengths cause index-out-of-bounds later. Message: 'Keys and frequencies must have the same length'.

Source

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

                    long currentCost = frequencySum + leftCost + rightCost;

                    if (currentCost < optimalCost[start][end]) {
                        optimalCost[start][end] = currentCost;
                        root[start][end] = currentRoot;
                    }
                }
            }
        }

        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]));

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Assert keys.length == frequencies.length at the point of construction and fail loudly there.
  2. Generate both arrays from a single source (zip keys with frequencies) so they cannot diverge.
  3. Add a defensive length check in tests/fixtures.

Example fix

// before
int[] keys = {10,20,30};
int[] freq = {4,2}; // mismatched
OptimalBinarySearchTree.optimize(keys, freq);

// after
if (keys.length != freq.length) {
    throw new IllegalStateException("keys/freq length mismatch");
}
OptimalBinarySearchTree.optimize(keys, freq);
Defensive patterns

Strategy: validation

Validate before calling

if (keys.length != frequencies.length) {
    throw new IllegalArgumentException("keys/frequencies length mismatch");
}
// then call optimize(keys, frequencies)

Type guard

keys != null && frequencies != null && keys.length == frequencies.length

Prevention

When it happens

Trigger: Building keys and frequencies from two different data sources that drifted; removing a key without removing its frequency or vice versa; off-by-one when copying subarrays.

Common situations: Editing a hand-written test fixture; merging data from two queries that should be zipped but weren't; CSV import with a ragged row.

Related errors


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