ForHosting KIT · Developer Utilities

Huffman code length calculator

Enter the frequencies 5, 9, 12, 13, 16 and 45 and get optimal Huffman code lengths of 4, 4, 3, 3, 3 and 1: 224 bits in total and 2.24 bits per symbol on average, next to the entropy for comparison. Free in your browser.

  • Free
  • Runs in your browser
  • No sign-up
  • Your data stays on your device
Use it from WebAPIEmailTelegramApp soon
If you enter
Frequencies
5, 9, 12, 13, 16, 45
You get
Symbol count
6
Lengths
4, 4, 3, 3, 3, 1
Total frequency
100
Total bits
224

Huffman coding is the classic minimum-redundancy binary prefix code used inside ZIP, PNG, DEFLATE, JPEG, and countless teaching labs. Given how often each symbol appears, the algorithm assigns shorter bit-strings to frequent symbols and longer ones to rare symbols so that no code is a prefix of another. This Huffman code length calculator accepts a list of strictly positive frequencies, builds the optimal Huffman tree with a deterministic tie-break, and returns each symbol’s code length, the total number of encoded bits for the multiset of symbols, the average length, Shannon entropy in bits for comparison, redundancy, and the Kraft sum. A single-symbol alphabet receives length zero, the empty code that still satisfies the prefix property.

What optimal Huffman lengths mean and how the tree is built

A binary prefix code maps each alphabet symbol to a bit string such that no code is a proper prefix of another; that property lets a decoder parse a concatenated bit stream without separators. The construction is simple and exact: place every symbol in a priority queue keyed by frequency; repeatedly extract the two lightest nodes, create a parent whose weight is their sum, and reinsert the parent until one root remains. The code length of a leaf is its depth in that tree.

When two nodes share the same weight, this implementation breaks ties by a stable insertion identifier so that identical inputs always produce identical length vectors across runtimes. For one symbol the optimal length is zero: the empty code uses no bits and still forms a valid prefix code for a singleton alphabet. For two or more symbols every length is at least one.

The Kraft sum of two to the minus each length is at most one for any complete prefix code and is reported so you can spot-check Kraft’s inequality without rebuilding the tree yourself.

Where Huffman lengths help, and their limits

Information-theory courses and coding interviews use a Huffman code length calculator so students can check optimal depths and total bits without hand-drawing trees for every frequency table. Compression engineers compare average Huffman length against Shannon entropy when sizing headers, choosing static versus dynamic tables, or teaching why DEFLATE-style codes sit close to the entropy bound. Failed validation does not consume balance.

Keep alphabets within the published maximum, send strictly positive counts rather than mixing zeros that would need special casing, and pin the returned lengths array in tests.

Classroom and interview practice

Students paste positive symbol frequencies and verify optimal Huffman lengths, total bits, and average length against hand-drawn trees.

Compression design checks

Engineers compare Huffman average length to Shannon entropy on empirical histograms before choosing static tables or fixed codes.

How do I compute Huffman code lengths from frequencies?

Send a non-empty array of strictly positive frequencies.

What length does a single symbol get?

Length zero. A one-symbol alphabet needs no bits under a minimum-redundancy prefix code; the empty code is valid and optimal.

Are zero frequencies allowed?

Omit unused symbols or send only strictly positive counts.

Does the tool return the actual 0/1 bit strings?

No. It returns optimal lengths and aggregates (total bits, average length, entropy, Kraft sum). You can assign any left/right labeling that respects those depths.

Why is the average code length above the entropy?

Shannon entropy is a lower bound on the average length of any code that can be decoded without ambiguity. Redundancy is the average length minus the entropy, so it is never negative, and a small value means the code is close to the best possible.

Everything on this page is available programmatically. This section is for teams who want to wire it into their own systems; everyone else can just use the tool above.

POSThttps://api.kit.forhosting.com/dev/huffman-code-length

Prefer to automate it? One authenticated POST creates the task; the result comes back by webhook or a signed link. The same capability also runs here on the web, by email and from Telegram — and soon from our app too.

curl -X POST https://api.kit.forhosting.com/dev/huffman-code-length \
  -H "Authorization: Bearer $KIT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"frequencies":[5,9,12,13,16,45]}'
{
  "frequencies": [
    5,
    9,
    12,
    13,
    16,
    45
  ]
}
{
  "task_id": "tsk_a1b2c3d4e5f6a1b2c3d4e5f6",
  "type": "dev.huffman_code_length",
  "status": "queued",
  "_links": {
    "result": "/tasks/tsk_…/result"
  }
}

The API is asynchronous: the call returns a task_id immediately and the result arrives by webhook. Polling is capped at 1 req/s per task.

Per request$0.002

Published price — no tokens, no invented credits. A failed task is never charged.

HTTPCodeMeaning
401unauthorizedMissing or invalid API key.
402insufficient_balanceYour balance doesn't cover the task price.
404unknown_typeThat task type doesn't exist.
429rate_limitedToo many requests. Use the webhook instead of polling.

The free browser path and the prepaid API share one pure analytic module, so homework oracles and production pipelines never disagree on lengths. Failed validation raises invalid_input and is not billed.

What optimal Huffman lengths mean and how the tree is built

Among all binary prefix codes, a Huffman code minimizes the weighted path length Σ frequency_i times length_i for a given positive frequency vector. The returned total_bits equals the sum of frequency times length and is the exact bit cost of encoding a multiset whose counts match the frequencies. Average length is total_bits divided by total frequency; Shannon entropy in bits is a lower bound on average length for any uniquely decodable code, so redundancy_bits equals average length minus entropy and is always non-negative within floating precision.

Input contract, response fields, aliases, and error behaviour

POST a JSON body with frequencies as a non-empty array of strictly positive finite numbers; aliases freqs, weights, counts, and freq are accepted, and a comma or whitespace separated string works for simple text forms. Optional labels (aliases symbols, names, alphabet) may supply a parallel array of non-empty strings of the same length for human-readable rows. Zero, negative, missing, empty, and non-finite frequencies fail with invalid_input naming the bad index. More than four thousand ninety-six symbols is rejected to keep Worker and browser paths fast. On success the body includes symbol_count; the cleaned frequencies array; lengths in the same order; total_frequency; total_bits; average_length; min_length and max_length; shannon_entropy_bits; redundancy_bits; kraft_sum; method set to huffman_optimal_lengths; formula summarizing the depth rule; optional labels when provided; and symbol_rows with index, frequency, length, bits, and optional label per symbol. Classic textbook frequencies five, nine, twelve, thirteen, sixteen, forty-five yield total_bits two hundred twenty-four and average length two point two four bits per symbol under this deterministic combine order. Pair the lengths with your own bit-string assignment if you need explicit zero-one codes; this endpoint returns lengths and aggregates only, not a particular left-zero versus right-zero labeling of branches.

CI oracles for codec tests

Pipelines pin deterministic total_bits and lengths arrays so histogram or alphabet changes fail tests immediately.

What does the Huffman code length calculator cost?

The browser tool is free. API requests use prepaid KIT balance at $0.002 per successful call; invalid input is not billed.

Read the full KIT documentation →