TheAlgorithms/Java · error · IllegalArgumentException

Malformed encoded string: incomplete sequence ending.

Error message

Malformed encoded string: incomplete sequence ending.

What it means

After consuming all bits, HuffmanCoding.decode checks that the traversal returned to the root — meaning the last sequence of bits ended exactly on a leaf node. If current != root, the payload ended mid-code (trailing bits with no complete leaf), which indicates truncation or corruption, so the library rejects it.

Source

Thrown at src/main/java/com/thealgorithms/compression/HuffmanCoding.java:238

            return sb.toString();
        }

        Node current = root;
        for (char bit : encodedText.toCharArray()) {
            if (bit != '0' && bit != '1') {
                throw new IllegalArgumentException("Encoded text contains invalid characters: " + bit);
            }

            current = (bit == '0') ? current.left : current.right;

            if (current.isLeaf()) {
                sb.append(current.ch);
                current = root;
            }
        }

        if (current != root) {
            throw new IllegalArgumentException("Malformed encoded string: incomplete sequence ending.");
        }

        return sb.toString();
    }

    /**
     * Retrieves the generated Huffman dictionary mapping characters to their binary codes.
     *
     * @return An unmodifiable map containing the character-to-binary-code mappings to prevent
     * external mutation of the algorithm's state.
     */
    public Map<Character, String> getHuffmanCodes() {
        return huffmanCodes;
    }
}

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Use the exact full bit string produced by encode without truncation.
  2. Round-trip test encode->decode to confirm payload integrity.
  3. Store the encoded length alongside the payload so truncation is detectable.

Example fix

// before
String dec = hc.decode(encoded.substring(0, encoded.length() - 1)); // truncated

// after
String dec = hc.decode(encoded); // full, complete sequence
Defensive patterns

Strategy: validation

Validate before calling

// Detect trailing incomplete sequence by checking length is a multiple of max code length is not robust;
// best defense: use the intact encode() output unchanged.
String dec = hc.decode(encodedText); // pass the full, untruncated bit string

Prevention

When it happens

Trigger: Decoding "010" with a tree whose valid codes are all 2 bits long (the trailing '0' leaves the walker stranded); a payload truncated by one or more bits; bits dropped during transport.

Common situations: The encoded string was truncated in storage/transit; bits were accidentally dropped or appended; the payload was hand-edited and left incomplete.

Understand the failure class

Related errors


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