🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101

Huffman file compressor

Compress and decompress real text files with Huffman coding and show how much space you saved.

Advanced⏱ 10–14 hoursđŸĒœ 7 stepsC++ or Java or PythonPriority queueBits

What you'll learn

  • ◆Greedy algorithms and priority queues
  • ◆Binary trees and prefix codes
  • ◆Bit-level file I/O

What you'll build

  • ✓compress file.txt → file.huf
  • ✓decompress back to the exact original
  • ✓Prints compression ratio
  • ✓Handles any byte, not just letters

Step-by-step guide

  1. 1

    Count frequencies

    Read the file as bytes; count each of the 256 values.

  2. 2

    Build the tree

    Push a leaf per byte into a min-heap by frequency; repeatedly pop two, join them under a new node, push back.

  3. 3

    Make codes

    Walk the tree: left = 0, right = 1; store the code string for each byte.

  4. 4

    Write bits

    Pack codes into bytes with a bit buffer; write a header with the frequency table and the original length.

  5. 5

    Decompress

    Rebuild the tree from the header, read bits, walk from the root to a leaf, output the byte, repeat.

  6. 6

    Verify

    Compare the original and decompressed files byte by byte (or with a hash).

  7. 7

    Measure

    Report sizes and ratio; try a text file, an image and an already zipped file and explain the results.

🚀 Make it stand out

  • +Canonical Huffman codes for a smaller header
  • +Compare with gzip
  • +Add a progress bar for big files