Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Lossless compression: run-length, variable-length and dictionary coding

Lossless compression reduces data without losing any information using run-length encoding, variable-length (prefix) codes like Huffman, and dictionary methods such as LZ77/LZ78—each has clear algorithms, performance bounds, and typical exam-style traces.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Lossless compression is used when exact original data must be recovered: textual data, program files, some images (e.g. medical, technical drawings) and intermediate data in multimedia pipelines. Engineers implement and choose these methods in codecs, file formats and network protocols where bandwidth or storage is limited but exact reconstruction is required.

Key ideas

Start from first principles: a source emits a sequence of discrete symbols from an alphabet. Compression replaces sequences of source symbols by shorter representations so that the original can be exactly recovered.

  • Compression ratio: ratio of compressed size to original size. Defined later precisely.
  • Lossless: reconstruction of the original sequence is exact; no information is discarded.
  1. Run-length coding (RLE)
  • Definition: Run-length encoding (RLE) represents consecutive repeated symbols (a run) by a pair (symbol, run-length) or by a run-length alone when the symbol is implied. It assumes many long runs of identical symbols.
  • Use assumption: input must contain long runs; otherwise RLE can expand data.
  • Draw for an exam: a horizontal sequence of symbols; group identical adjacent symbols; above each group write its length and the symbol.
  1. Variable-length coding and prefix codes
  • Definition: A code maps each source symbol to a binary string (codeword). A code is prefix (or instantaneous) if no codeword is a prefix of another; prefix codes are decodable without lookahead.
  • Kraft inequality (exact statement): For any binary prefix code with codeword lengths l1,...,ln, sum_{i=1..n} 2^{-l_i} ≤ 1. Conversely, any set of positive integer lengths satisfying this inequality can be assigned codewords that form a prefix code (constructive proof using a binary tree).
  • Entropy and average length: Given symbol probabilities p_i, the entropy H is the lower bound on average code length per symbol (in bits): H = -sum p_i log2 p_i. For any prefix code with average length L = sum p_i l_i, we have the bound H ≤ L (information inequality) and there is a prefix code (practical Huffman code) with H ≤ L < H + 1 (Shannon bound for optimal prefix codes; more precise bounds exist with block coding).
  • Huffman coding: Huffman algorithm builds a binary tree by repeatedly merging the two least-probable symbols/nodes; it produces an optimal prefix code minimizing average length L among all prefix codes for the given symbol probabilities (assumes symbol probabilities are known and coding is symbol-by-symbol, not block coding).
  • Shannon–Fano coding: similar goal but not guaranteed optimal; construct code by recursively partitioning symbols into two groups with (near-)equal total probability.
  • Arithmetic coding: encodes whole sequences into a fractional interval and can approach entropy arbitrarily closely (expected length within ≈1/N bits of H for block length N); widely used in modern codecs (e.g., CABAC in H.264/HEVC, JPEG 2000); not a prefix code but uniquely decodable; supports adaptive modeling.
  • For exams draw: binary tree produced by Huffman; label leaves with symbols and edge bits 0/1; read codewords by root-to-leaf paths.
  1. Dictionary coding (Lempel–Ziv family)
  • General idea: replace substrings by references to previously seen data kept in a dictionary. This exploits repeated substrings rather than repeated single symbols.
  • LZ77 (sliding-window): outputs triples (offset, length, next-symbol) where offset points back into a sliding window of already encoded data. Dictionary is implicit (past data in window). Useful for streaming and low-memory decoders.
  • LZ78: builds an explicit dictionary of previously seen phrases. Each output is a pair (index, next-symbol), where index points to the longest matching dictionary entry; then you add (match + next-symbol) as a new dictionary entry.
  • LZW (Lempel–Ziv–Welch): variant of LZ78 where the next-character is not sent separately; the dictionary is initialised with all single symbols and each new entry is previousMatch + firstChar(currentMatch) (outputs are indices only). Widely used in GIF (with CLEAR/END codes) and classic UNIX compress.
  • For exams draw: for LZ77 draw the sliding window and show offsets; for LZ78 draw the dictionary growing with index numbers.

Assumptions behind each method: RLE assumes long runs; variable-length coding assumes known symbol probabilities and independence (or we consider symbol-by-symbol coding); dictionary methods assume repeated substrings and operate without prior probability model.

Formulas

H = - sum_{i} p_i log2 p_i

  • H: entropy of the discrete source, in bits per symbol; p_i: probability of symbol i (dimensionless). Applies to memoryless (i.i.d.) sources for the single-letter entropy.

L = sum_{i} p_i l_i

  • L: average code length in bits per source symbol; l_i: length (in bits) of codeword for symbol i; p_i: probability of symbol i.

H ≤ L < H + 1

  • Bound on average length L for an optimal prefix code (Huffman) under symbol-by-symbol coding; units bits/symbol. Assumes known p_i.

sum_{i} 2^{-l_i} ≤ 1

  • Kraft inequality: l_i are positive integer codeword lengths for a binary prefix code.

Compression ratio = (compressed size) / (original size)

  • Unitless (often expressed as percentage or decimal). Works for same units (bytes or bits).

For RLE when storing run length in fixed k bits: Encoded bits per run = s + k, where s = ceil(log2 |Alphabet|) bits to store the symbol (s = 1 for a binary alphabet). Total encoded bits = sum_runs (s + k). Units: bits. Specific format varies.

Worked examples

Example 1 — Run-length encoding (numeric trace) Input (a row of pixels): 0 0 0 1 1 1 1 0 0 0 Step 1: Group runs: (3 of 0), (4 of 1), (3 of 0). If we store as pairs (symbol, length) with symbol=1 bit and length in one byte (8 bits):

  • Original size = 10 symbols = 10 bits (if binary) or 10 bytes if 1 byte per symbol. Use bits: 10 bits.
  • Encoded size = for three runs, each pair uses 1 + 8 = 9 bits; total 3 × 9 = 27 bits. (Here encoding expanded because lengths used 8 bits.) Better choice: store alternating run lengths starting with symbol 0: lengths 3,4,3 as, say, 4-bit fields if known max ≤15: encoded bits = 1 (start-symbol bit) + 3×4 = 13 bits, which is slightly larger than the original 10 bits. RLE helps when runs are long relative to overhead. Final answer: RLE helps only when runs are sufficiently long compared to header overhead.

Example 2 — Huffman coding (numerical) Symbols and probabilities: A:0.40, B:0.30, C:0.20, D:0.10. Step 1: Combine least probable nodes: C(0.20)+D(0.10)=0.30 -> node X(0.30). Step 2: Now nodes: A(0.40), B(0.30), X(0.30). Combine two smallest (B and X) -> node Y(0.60). Step 3: Combine A(0.40)+Y(0.60)=1.00. Assign bits (one side 0, other 1):

  • A: 0
  • Y: 1 -> within Y: B: 10, X: 11 -> within X: C: 110, D:111 Codewords: A=0 (l=1), B=10 (l=2), C=110 (l=3), D=111 (l=3). Average length L = 0.4·1 + 0.3·2 + 0.2·3 + 0.1·3 = 0.4 + 0.6 + 0.6 + 0.3 = 1.9 bits/symbol. Entropy H = −(0.4 log2 0.4 + 0.3 log2 0.3 + 0.2 log2 0.2 + 0.1 log2 0.1) Compute: 0.4·1.3219=0.5288; 0.3·1.737=0.5211; 0.2·2.3219=0.4644; 0.1·3.3219=0.3322; sum H≈1.8465 bits/symbol. We have H≈1.8465 ≤ L=1.9 < H+1≈2.8465 — bound holds. Average savings vs fixed 2-bit code: fixed-length 2 bits → compression = 1.9/2 = 95% so 5% saving. Final answer: Huffman gives L=1.9 bits/symbol here, close to entropy. (Values rounded; check logs in exam.)

Example 3 — LZ78 trace (algorithmic) Input string (symbols letters): A B A A B A B A A B Assume index 0 denotes the empty string and we use a special end marker EOF when the input ends immediately after a dictionary phrase. Start dictionary empty; index numbers start at 1. Stepwise:

  1. Position 1: 'A' is not yet in dict → output (0,'A'); add entry1='A'.
  2. Position 2: 'B' is not yet in dict → output (0,'B'); add entry2='B'.
  3. Position 3: longest match is 'A' (index1); next char 'A' makes new phrase 'AA' → output (1,'A'); add entry3='AA'. Advance past "AA".
  4. Position 5: longest match is 'B' (index2); next char 'A' makes 'BA' → output (2,'A'); add entry4='BA'. Advance past "BA".
  5. Position 7: longest match is 'BA' (index4); next char 'A' makes 'BAA' → output (4,'A'); add entry5='BAA'. Advance past "BAA".
  6. Position 10: remaining single 'B' and then end-of-input → output (2, EOF). No new dictionary entry is added for the EOF step. Final encoded output: (0,'A') (0,'B') (1,'A') (2,'A') (4,'A') (2, EOF) This complete trace shows how substrings are replaced by indices (plus a terminating EOF symbol when needed).

Note: exam answer must show exact step-by-step consumption; above is model — please verify the exact steps for the chosen input.

Common mistakes

  • Applying Huffman without checking prefix property or mis-assigning 0/1 edges arbitrarily and producing non-optimal tree merges (must always merge two smallest probabilities).
  • Forgetting to include the cost of storing codebook or run-length headers when computing true compressed size.
  • For RLE: counting runs incorrectly when symbol switches; forgetting to handle runs longer than the chosen field size (overflow).
  • In LZ traces: not updating the dictionary exactly after consuming matched substring + next character; off-by-one errors in consumed symbols.
  • Using Shannon–Fano when Huffman should be used for optimal average length; not stating assumptions (memoryless source, symbol-by-symbol coding).

For your exam

Typical question types

  • Definitions and short notes: define RLE, prefix code, entropy, Kraft inequality, LZ77 vs LZ78.
  • Derivation/proof: prove Kraft inequality; show H ≤ L for any prefix code; derive Huffman algorithm steps and prove optimality sketch.
  • Numericals: build Huffman code for given symbol probabilities, compute H, L and compression; compute encoded size for RLE with given run-length field size; trace LZ78/LZW/LZ77 on a sample string.
  • Programs/algorithms: pseudo-code for Huffman or LZ78 and explain complexity O(m log m) to build the Huffman tree with a priority queue for alphabet size m (plus O(N) to count frequencies over N input symbols), and O(N) average for LZ77 with efficient search.
  • Diagrams: drawing Huffman tree, sliding window in LZ77, or dictionary table growth in LZ78. What full-marks answers include
  • Clear statement of definitions with bold terms; list assumptions (memoryless source, known probabilities, field sizes); correct step-by-step construction; units and final numeric values with correct rounding; diagrams labelled (nodes, probabilities, bits) when needed; and discussion of practicality (overhead, when method helps).

Quick check

  1. What is a prefix code?
  2. State the Kraft inequality for binary codes.
  3. In Huffman coding, which two nodes are merged at each step? Answers: A prefix code is a code where no codeword is a prefix of another; Kraft inequality: sum 2^{-l_i} ≤ 1 for codeword lengths l_i; Huffman merges the two nodes with smallest probabilities (or weights) at each step.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?