Compress String (RLE) in C, C++, Java & Python – Code with Explanation & Examples in Short and Simple

   

C Program

#include <stdio.h>
#include <string.h>

int main() {
    char str[100];
    scanf("%s", str);

    int n = strlen(str);
    for (int i = 0; i < n; i++) {
        int count = 1;
        while (i < n - 1 && str[i] == str[i + 1]) {
            count++;
            i++;
        }
        printf("%c%d", str[i], count);
    }
    return 0;
}

C Output

Input:  
aaabbcccc  

Output:  
a3b2c4


C++ Program

#include <iostream>
using namespace std;

int main() {
    string str;
    cin >> str;

    for (int i = 0; i < str.size(); i++) {
        int count = 1;
        while (i < str.size() - 1 && str[i] == str[i + 1]) {
            count++;
            i++;
        }
        cout << str[i] << count;
    }
    return 0;
}

C++ Output

Input:  
xxxyyyzzzz 

Output:  
x3y3z4


JAVA Program

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        for (int i = 0; i < str.length(); i++) {
            int count = 1;
            while (i < str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
                count++;
                i++;
            }
            System.out.print(str.charAt(i) + "" + count);
        }
    }
}

JAVA Output

Input:  
ppqqqqrr 

Output:  
p2q4r2


Python Program

s = input()
i = 0
while i < len(s):
    count = 1
    while i < len(s)-1 and s[i] == s[i+1]:
        count += 1
        i += 1
    print(s[i] + str(count), end="")
    i += 1

Python Output

Input:  
kkkklllmm 

Output:  
k4l3m2


In-Depth Explanation
Example
Consider the input "aaabbcccc". If we compress it using Run Length Encoding (RLE), we get "a3b2c4". Rather than storing every character separately, we store the character and how many times it occurs in succession. For example, "aaa" turns into "a3", "bb" turns into "b2", and "cccc" turns into "c4". Thus, the string is minimized in size if there are repeated characters.

Real-Life Analogy
Consider including the same items. If you venture out and purchase 10 apples, you don't say "apple, apple, apple…" ten times. You just say "10 apples." This is what RLE does — it counts the repeating items (characters) in succession and depicts them in a condensed way.

Another analogy is when you watch cricket or football highlights — instead of showing every ball or every second, only the key events are compressed into a summary. Similarly, RLE summarizes long repetitive sequences.

Why It Matters
RLE is the most straightforward compression algorithm employed by computer science. It does not always shrink size (e.g., "abcd" shrinks to "a1b1c1d1", which is longer), but where there are a lot of repeating patterns in the data, it significantly minimizes the space needed for storage. The BMP (bitmap graphics) file type, TIFF, and fax machines have all traditionally utilized RLE to conserve memory and transmission time. 

Learning Insights
From a coding point of view, RLE teaches string traversal, counting, and grouping of consecutive elements. These are crucial concepts to solve string-based interview problems like group anagrams, compress-decompress problems, encoding of DNA sequences, and log compression. It also makes you consider when compression is useful and when it may not be helpful.

Interview Relevance
During interviews, this problem comes up in variations as:

Implement string compression (RLE).

Decompress an RLE-compressed string.

Maximize memory for repeated patterns.

Expand RLE to binary strings (extremely popular in data structures and computer logic interviews).

A twist that is often used is that you need to deal with edge cases such as empty strings, non-repeated strings, or numeric characters within the string.

Real-World Application
Image Compression: RLE is employed in file formats such as PCX, BMP, and TIFF, where large portions of an image can consist of the same color.

Text Storage: When you have logs containing duplicated characters (such as "0000000"), RLE saves space.

Data Transmission: Fax machines and basic printers used to use RLE because it is quick and minimizes data to be transmitted.

Game Development: Ancient 8-bit and 16-bit games frequently employed RLE to compress sprites in order to conserve cartridge memory.

SEO-Optimized Closing
Run Length Encoding string compression is a programming cardinal rule, found prevalently in data compression and string manipulation operations. Learning how to compress strings with RLE in C, C++, Java, and Python not only educates beginners on string walking and counting logic but also on how actual file formats such as BMP and TIFF compress and manage data efficiently. Solving RLE problems enhances problem-solving ability for coding interview, competitive programming, and practical applications where minimizing the use of memory and optimizing storage are critical. If you aim to master coding string problems, the RLE string compression algorithm is among the most critical topics to master and know in depth.