Everything on the site.

Big-O notationAlgorithms · Count the steps in real loops, then compare n, n log n, n² and 2ⁿ on a live chart.RecursionAlgorithms · Watch frames push and pop on the call stack for factorial and Fibonacci.BFS vs DFSAlgorithms · A queue against a stack: draw a graph and see which order each search visits it in.Sorting algorithmsAlgorithms · Seven sorts on the same input, with comparison, swap and write counts side by side.Binary searchAlgorithms · Halve the range, probe the middle, repeat: with lo, mid and hi drawn on the array.Sets, relations and functionsDiscrete maths · Shade any set expression on a Venn diagram and test a relation for its properties.Proof by inductionDiscrete maths · Four worked proofs revealed one step at a time, and a broken one to diagnose.CombinatoricsDiscrete maths · An exact nPr and nCr calculator, and a Pascal’s triangle that shows its own addition rule.Boolean algebraDiscrete maths · The laws, De Morgan, and normal forms, with a truth-table generator built in.Finite-state machinesTheory · Build a DFA in a table, see it drawn, and run strings through it one symbol at a time.Domain theoryTheory · Why recursion needs least fixed points, and how CPOs, Scott continuity and powerdomains supply them.Truth table generatorTools · Expression in, truth table out: with DNF, CNF, a minimal form and LaTeX.Graph traversal visualiserTools · Draw a graph, then animate BFS, DFS and Dijkstra with the frontier shown.Recursion tree visualiserTools · Paste a recursive function or a recurrence and see its call tree and call count.Gradient descentML maths · Drag the starting point, set the learning rate, and watch it converge or blow up.Vectors and embeddingsML maths · Bend the plane with a 2×2 matrix and measure how close toy word vectors are.Softmax and cross-entropyML maths · Edit the logits and watch the probabilities, the loss and the gradient update live.Attention mechanismML maths · Q, K and V for three tokens, a live score heatmap, and the weighted sum of values.Image to video attentionML maths · One photo, 16 frames: switch reference attention on or off and watch the colours hold or drift.Formatting a CS paper in LaTeXLaTeX · Page limits, \documentclass, front matter, theorem environments and the bibliography.Camera-ready checklistLaTeX · Fonts embedded, PDF/A, copyright form, source bundle, and why final versions get rejected.LaTeX templatesLaTeX · Where the official classes live, plus a minimal article template you can copy.Boolean algebra calculatorTools · A Boolean expression simplifier that names the law used at every step.K-map solverTools · Fill in a Karnaugh map and see the groups, the minimal SOP and POS, and the essential terms.Logic gate simulatorTools · Wire up gates, flip the switches, and get the truth table and expression of your circuit.Regex to NFA converterTools · Type a regular expression and watch Thompson’s construction build its NFA, fragment by fragment.NFA to DFA converterTools · Enter an NFA or a regex and step through the subset construction, then minimise the DFA.DFA simulatorTools · Edit a DFA, run strings through it step by step, batch-test them and share the machine as a link.Regular expressions to automataTheory · Regex to NFA to DFA to minimal DFA, worked through on one example with every set shown.The halting problemTheory · Why no program can tell whether every program halts, with the paradox program played out.Pigeonhole principleDiscrete maths · n pigeons, k holes: why some hole gets ⌈n/k⌉, and the surprising things that follows from it.Dijkstra’s algorithmAlgorithms · Shortest paths with a priority queue: a worked table, a proof, and a graph you can redraw.Hash functionsAlgorithms · Keys in, buckets out: hash a word four ways, then watch chaining and probing handle collisions.Sorting algorithm visualizerTools · Up to seven sorts race on the same data, then step through any one of them line by line.LaTeX table generatorTools · Type or paste a table, merge cells, pick booktabs, and copy clean tabular code.Combination calculatorTools · Exact nCr with the cancelling shown, combinations with repetition, and a full list for small n.Permutation calculatorTools · nPr, nʳ, anagrams like MISSISSIPPI and round-table seatings, with exact working.AVL tree visualizerTools · Insert, delete and search, then replay every balance factor and rotation step by step.IEEE 754 converterTools · Decimal to float bits and back, with the exact stored value and why 0.1 isn’t exact.Two’s complement calculatorTools · Signed integers to bits and back, with the working, other encodings and overflow checks.Power set calculatorTools · Every subset of your set, sorted by size or bitmask, with 2ⁿ counted exactly.Huffman coding calculatorTools · Text or frequencies in, Huffman tree and codes out, with every merge shown in order.LaTeX matricesLaTeX · pmatrix, bmatrix, augmented and large matrices, each with copyable code and its result.AlgorithmsSection · Step-through visualisations of sorting, searching, recursion, graph traversal, Dijkstra’s algorithm, hash functions and Big-O growth, with pseudocode that follows along.Discrete mathsSection · Sets, relations and functions, proof by induction, counting, the pigeonhole principle and Boolean algebra, explained with worked examples and interactive checkers.TheorySection · Finite-state machines, regular expressions and automata, the halting problem, and the mathematical semantics of programming languages, explained from first principles.ML mathsSection · Gradient descent, vectors and embeddings, softmax, attention and image to video models, each with a formula, a worked numeric example and a live version.ToolsSection · Free browser tools: truth tables, K-maps, logic gates, nCr, power sets, regex to DFA, sorting, graph and AVL tree visualisers, IEEE 754, two’s complement and Huffman codes.LaTeXSection · How to format a CS conference or workshop paper in LaTeX, a camera-ready checklist, a minimal template you can adapt, and how to typeset matrices.
Free tool

Huffman coding calculator: build the tree and code table

Type a message, or a table of symbol frequencies, and this calculator builds the Huffman tree one merge at a time, then gives the code for every symbol, the encoded bits, and how many bits you save over fixed-length and ASCII codes. Step through each merge to check your own answer to a textbook exercise.

Interactive: Step-through Huffman tree builder with code table and encoderUpdated

Huffman coding calculatorType a message, or symbols with their frequencies. Then step through the merges that build the tree.

  • Two lightest trees, just merged
  • New parent node
  • Leaf (symbol)

Queue of trees (lightest first)

Size

0Huffman bits
0Fixed-length bits
08-bit ASCII bits

Code table

SymbolWeightCodeBitsWeight × bits

Encoded message

What Huffman coding does

A fixed-length code gives every symbol the same number of bits: 8 bits per character in ASCII, or 3 bits each if a message only uses the letters a to f. Huffman coding, devised by David Huffman as a student in 1952, gives short codes to frequent symbols and longer codes to rare ones, like Morse code does. For a given set of symbol frequencies, no code that assigns each symbol its own fixed bit string produces a shorter encoding.

It is a prefix code: no code word is the beginning of another. That means an encoded bit string can be decoded without any separators. Read bits until they match a code word, output that symbol, and start again. The code words are exactly the root-to-leaf paths of a binary tree, with 0 for each left branch and 1 for each right branch, and the prefix property holds because symbols live only at leaves.

The algorithm

  1. Make one single-node tree per symbol, weighted by its frequency, and put them all in a priority queue.
  2. Remove the two trees with the smallest weights.
  3. Join them under a new parent whose weight is the sum of theirs, and put the new tree back in the queue.
  4. Repeat steps 2 and 3 until one tree is left. With kk symbols that takes k−1k - 1 merges.
  5. Label left branches 0 and right branches 1. Each symbol’s code is the path from the root to its leaf.

With a binary heap as the priority queue, each removal and insertion costs O(log⁡k)O(\log k), so building the tree takes O(klog⁡k)O(k \log k) time. Counting the frequencies takes one pass over the message.

Worked example: abracadabra

  1. Count: a appears 5 times, b 2, r 2, c 1 and d 1, for 11 symbols in total.
  2. Merge c (1) and d (1) into a tree of weight 2. The queue is now b 2, r 2, {cd} 2, a 5.
  3. Merge b (2) and r (2) into weight 4. Ties are common; any choice among equal weights gives an optimal code.
  4. Merge {cd} (2) and {br} (4) into weight 6.
  5. Merge a (5) and the tree of weight 6 into the root, weight 11.
  6. Read off the codes: a = 0, b = 110, r = 111, c = 100, d = 101.
  7. Total: 5×1 + 2×3 + 2×3 + 1×3 + 1×3 = 23 bits, against 11 × 3 = 33 bits with a 3-bit fixed code and 88 bits in ASCII. The message encodes as 01101110100010101101110.

This is the calculator’s starting example. Press play to watch the four merges.

Measuring the result

If symbol ii has frequency fif_i and its code has ℓi\ell_i bits, the encoded message has ∑ifiℓi\sum_i f_i \ell_i bits, and the average code length is that total divided by ∑ifi\sum_i f_i. Shannon’s source coding theorem gives a lower bound: no prefix code can average fewer bits per symbol than the entropy

H=−∑ipilog⁡2pi,pi=fi∑jfj.H = -\sum_i p_i \log_2 p_i, \qquad p_i = \frac{f_i}{\sum_j f_j}.

A Huffman code always satisfies H≤ℓˉ<H+1H \le \bar\ell < H + 1. It equals the entropy exactly when every probability is a power of ½, as in the “Probabilities” example with weights 0.5, 0.25, 0.25. The calculator prints the average and the entropy side by side.

The classic textbook table (a 45, b 13, c 12, d 16, e 9, f 5, per 100 characters) needs 300 bits with a 3-bit fixed code and 224 with Huffman coding, a saving of about 25%.

Why the greedy choice is optimal

Two facts make the proof work, and together they show by induction on the number of symbols that Huffman’s code is optimal:

  • The two rarest symbols can be siblings at the deepest level. In any optimal tree, swapping a rare symbol into the deepest leaf never increases the total, because the rarer symbol then pays for the longer code.
  • Merging them reduces the problem. Replace the two rarest symbols x,yx, y by one symbol of weight fx+fyf_x + f_y. An optimal tree for the smaller problem, with that leaf split back into xx and yy, is optimal for the original, because the split adds exactly fx+fyf_x + f_y to the cost whichever tree you start from.
Ties and different answers When two trees have equal weight, either can be taken first, and the left/right choice at each merge is arbitrary. Different choices give different codes and different tree shapes, but always the same total number of bits. So if your answer to an exercise differs from the textbook’s, compare the total and the code lengths, not the bit strings. This calculator takes the tree created earlier first and puts the first tree taken on the left.

Where Huffman coding is used

Huffman codes are the final stage of DEFLATE (used by ZIP, gzip and PNG), of baseline JPEG, and of MP3 audio. In practice they are combined with other steps: DEFLATE first replaces repeated strings with back-references (LZ77) and then Huffman-codes what remains, and JPEG Huffman-codes quantised frequency coefficients. Huffman coding only exploits how often each symbol appears, not patterns such as “q is followed by u”, which is why it is rarely used alone.

Two practical details: the decoder needs the code as well as the bits, so files store the code lengths (a “canonical” Huffman code can be rebuilt from lengths alone); and because every code is a whole number of bits, a symbol with probability 0.99 still costs at least 1 bit. Arithmetic coding and asymmetric numeral systems get closer to the entropy in that case.

Using the calculator

  • Text to encode counts every character, including spaces (shown as ␣) and capitals, and shows the encoded bit string.
  • Frequency table takes symbol:weight pairs separated by commas or new lines. Weights can be counts or probabilities.
  • Step through the merges with the player controls or the arrow keys. The queue panel shows the trees waiting to be merged, lightest first.
  • The address bar updates as you go, so you can share a link to your example.

Prefix codes and binary trees connect to other pages here: a prefix code is decoded by a small finite-state machine, and the codes are a form of the binary strings counted on the power set calculator page.

References

  1. D. A. Huffman, “A method for the construction of minimum-redundancy codes”, Proceedings of the IRE 40(9), 1952, 1098–1101.
  2. T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022. Section 15.3, Huffman codes.
  3. T. M. Cover and J. A. Thomas, Elements of Information Theory, 2nd ed., Wiley, 2006. Chapter 5, data compression.
  4. K. Sayood, Introduction to Data Compression, 5th ed., Morgan Kaufmann, 2017. Chapter 3.