Discover how clever coding can shrink your messages and save precious space!
Why Huffman Encoding in DSA Typescript?
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.
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.
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.
const bitsPerChar = 8; const message = 'hello'; const encoded = message.split('').map(c => c.charCodeAt(0).toString(2).padStart(bitsPerChar, '0')).join('');
const huffmanCodes = { h: '10', e: '00', l: '01', o: '11' };
const message = 'hello';
const encoded = message.split('').map(c => huffmanCodes[c]).join('');It enables efficient data compression, saving space and speeding up communication without losing any details.
When you send a photo or text online, Huffman Encoding helps reduce file size so it uploads faster and uses less data.
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.