{"record":{"id":"2eb6a3c3361c0091","repo":"TheAlgorithms/Java","slug":"frequencies-must-be-non-negative","errorCode":null,"errorMessage":"Frequencies must be non-negative","messagePattern":"Frequencies must be non-negative","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/others/Huffman.java","lineNumber":97,"sourceCode":"     */\n    public static HuffmanNode buildHuffmanTree(char[] charArray, int[] charFreq) {\n        if (charArray == null || charFreq == null) {\n            throw new IllegalArgumentException(\"Character array and frequency array cannot be null\");\n        }\n        if (charArray.length == 0 || charFreq.length == 0) {\n            throw new IllegalArgumentException(\"Character array and frequency array cannot be empty\");\n        }\n        if (charArray.length != charFreq.length) {\n            throw new IllegalArgumentException(\"Character array and frequency array must have the same length\");\n        }\n\n        int n = charArray.length;\n        PriorityQueue<HuffmanNode> priorityQueue = new PriorityQueue<>(n, new HuffmanComparator());\n\n        // Create leaf nodes and add to priority queue\n        for (int i = 0; i < n; i++) {\n            if (charFreq[i] < 0) {\n                throw new IllegalArgumentException(\"Frequencies must be non-negative\");\n            }\n            HuffmanNode node = new HuffmanNode(charArray[i], charFreq[i]);\n            priorityQueue.add(node);\n        }\n\n        // Build the Huffman tree\n        while (priorityQueue.size() > 1) {\n            HuffmanNode left = priorityQueue.poll();\n            HuffmanNode right = priorityQueue.poll();\n\n            HuffmanNode parent = new HuffmanNode();\n            parent.data = left.data + right.data;\n            parent.c = '-';\n            parent.left = left;\n            parent.right = right;\n\n            priorityQueue.add(parent);\n        }","sourceCodeStart":79,"sourceCodeEnd":115,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/others/Huffman.java#L79-L115","documentation":"Thrown by Huffman.buildHuffmanTree inside the leaf-creation loop when charFreq[i] < 0. Huffman frequencies represent occurrence counts/weights used to build a min-priority queue; a negative weight breaks the priority ordering and would produce an invalid tree (potentially a non-optimal or cyclic structure).","triggerScenarios":"Passing a frequency array with a negative value — e.g., weights computed as a difference that went negative, a corrupted/deserialized table, or a signed-integer underflow in a counter.","commonSituations":"Frequency tables derived from deltas or signed adjustments, data corruption, or a counter that decremented below zero.","solutions":["Validate frequencies are non-negative at the point they are computed; clamp or reject negatives.","Sanitize the frequency table before building arrays (replace negatives with 0 or drop the symbol).","Audit the upstream counter logic for underflow."],"exampleFix":"// before\nint[] frq = computeWeights(input); // may contain negatives\nHuffman.buildHuffmanTree(syms, frq);\n\n// after\nint[] frq = computeWeights(input);\nfor (int i=0;i<frq.length;i++) if (frq[i] < 0) frq[i] = 0; // or throw\nHuffman.buildHuffmanTree(syms, frq);","handlingStrategy":"validation","validationCode":"for (int f : charFreq) {\n    if (f < 0) throw new IllegalStateException(\"Negative frequency \" + f);\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Clamp or reject negative weights where frequencies are computed.","Audit counter logic for underflow when frequencies derive from deltas."],"tags":["huffman","precondition","validation","negative-value","compression"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}