0
0
DSA Typescriptprogramming~3 mins

Why Huffman Encoding in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

Discover how clever coding can shrink your messages and save precious space!

The Scenario

Imagine you have a long text message to send, but your phone only allows a limited number of characters. You try to write each letter with the same number of bits, wasting space on common letters like 'e' and 't'. This makes your message too long to send easily.

The Problem

Using the same number of bits for every letter means you can't save space. It's like packing your suitcase with all items taking equal space, even if some are tiny. This wastes storage and slows down sending or saving data.

The Solution

Huffman Encoding gives shorter codes to common letters and longer codes to rare ones. It cleverly builds a tree to assign these codes, making the whole message smaller without losing any information.

Before vs After
Before
const bitsPerChar = 8;
const message = 'hello';
const encoded = message.split('').map(c => c.charCodeAt(0).toString(2).padStart(bitsPerChar, '0')).join('');
After
const huffmanCodes = { h: '10', e: '00', l: '01', o: '11' };
const message = 'hello';
const encoded = message.split('').map(c => huffmanCodes[c]).join('');
What It Enables

It enables efficient data compression, saving space and speeding up communication without losing any details.

Real Life Example

When you send a photo or text online, Huffman Encoding helps reduce file size so it uploads faster and uses less data.

Key Takeaways

Manual fixed-length codes waste space on common letters.

Huffman Encoding assigns shorter codes to frequent letters.

This reduces message size while keeping all information intact.