r/AskComputerScience • u/AdPsychological7065 • Jul 10 '26
LZ77 algorithm is making the compressed files bigger than original
I was recently toying around with some compression, just trying to understand it from the basics. I came to know about LZ77, LZ78, and LZW algorithms in the last couple of days, understood the algorithms, and when implementing LZ77, every time I try to compress a txt file, it is making the output file bigger. The compression is done right coz when I decompress the compressed file, I get the exact text.
Is there something I am missing to understand? Can anyone help me out and figure out what I am doing wrong?
1
Upvotes
29
u/Davidbrcz Jul 10 '26
A lossless compression algorithm must be reversible: given the compressed file, it must always be possible to recover the original file exactly. Therefore, the compression function must map different input files to different compressed outputs.
Now consider all files of a fixed size, say (n) bits. There are (2^n) such files. If every one of them could be compressed into fewer than (n) bits, there would be only (2^n - 1) possible compressed outputs (counting all bit strings of length less than (n)). Since there are fewer possible outputs than inputs, two different files would have to map to the same compressed output, making perfect decompression impossible.
Therefore, no lossless compression algorithm can make every file smaller. Any algorithm that compresses some files must necessarily leave others unchanged or even make them larger.
9
u/iamemhn Jul 10 '26 edited Jul 10 '26
You don't say what kind of file you were trying to compress. I guess you tried to compress either an encrypted file or a lossy media file (e.g. MP3 audio file, or H.264 files). Both formats have already been compressed as part of their reduction techniques so their footprint is already minimal. If you try to compress an already compressed file, the «outer» compression will add an absolutely useless, but not zero-sized, header and dictionary information.
5
u/pi_stuff Jul 10 '26
You might just have a bug in your code, where it isn't finding enough duplicates in the input even though it is doing the encoding correctly. Try running the same input through a standard compressor like gzip.
3
u/mxldevs Jul 10 '26
Your inputs might already be as compressed as it gets using that algo. I'd compare it to another program's output and see if it's the same
2
u/CowBoyDanIndie Jul 10 '26
Are there repeated words or at least 3+ letters that repeat? If the file is small, there might not enough matches to make up for the minimal overhead of the file structures. You need entropy encoding like huffman if there arent any simple patterns. Add some debug to spit out any pattern matches, or step through with debugger