Run Length Encoding (RLE) data compression algorithm

Run length encoding (RLE) is a very simple form of lossless data compression which runs on sequences having same value occurring many consecutive times and it encode the sequence to store only a single value and its count.


For example,

Consider a screen containing plain black text on a solid white background. There will be many long runs of white pixels in the blank space, and many short runs of black pixels within the text.


With a run length encoding (RLE) data compression algorithm applied to the above hypothetical scan line, it can be rendered as follows:


This can be interpreted as a sequence of twelve Ws, one B, twelve Ws, three Bs, etc.

The idea is to run a linear scan on the string and for each distinct character, we append the character and its consecutive occurrence in the output string.

Note that in worst case the size of output size will be just double of input size, so the algorithm can’t run in-place. eg. ABCD -> A1B1C1D1

Below is C++ and Java implementation of the idea –


Download   Run Code


Download   Run Code




1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

newest oldest most voted
Notify of

Hi, first I want to thank you for your post.
i am trying to run the code in code::blocks. Code::blocks to recognize the order to_String.
I think it use a older compiler than c++ 11.
So I tried to change the int to string by an other way, the problem is that how the result is 1A12B123C1D instead of your right result. My code change is:

Can you please help me. Thank you