Run Length Encoding and Decoding

Last Updated : 9 May, 2026

Given a string s, implement a function encode that performs run-length encoding on the string. Run-length encoding is a form of compression where consecutive occurrences of the same character are replaced by the character followed by the count of its occurrences.

Input: s = aaaabbbccc
Output: a4b3c3
Explanation: The character 'a' repeated 4 times consecutively and 'b' 3 times, 'c' also 3 times, so answer for this test case is a4b3c3.

Input: s = abbbcdddd
Output: a1b3c1d4
Explanation: The character 'a' is repeated 1 time, 'b' 3 times, 'c' 1 time and 'd' repeated 4 times, so answer for this test case is a1b3c1d4.

Try It Yourself
redirect icon

Using Iteration (Run-Length Encoding) - O(n) Time and O(n) Space

Follow the steps below to solve this problem:

  1. Pick the first character from the source string. 
  2. Append the picked character to the destination string. 
  3. Count the number of subsequent occurrences of the picked character and append the count to the destination string. 
  4. Pick the next character and repeat steps 2, 3 and 4 if the end of the string is NOT reached.

Below is the implementation of the above approach:

C++
#include <iostream>
#include <string>
using namespace std;

// Function to implement run length encoding
string encode(string &s)
{
    string result = "";
    int n = s.length();

    for (int i = 0; i < n; i++) {

        // Count occurrences of current character
        int count = 1;
        while (i < n - 1 && s[i] == s[i + 1]) {
            count++;
            i++;
        }

        // Append character and its count to result
        result += s[i];
        result += to_string(count);
    }

    return result;
}

// Driver code
int main()
{
    string str = "wwwwaaadexxxxxxywww";
    
    cout << encode(str);

    return 0;
}
C
#include <stdio.h>
#include <string.h>

// Function to implement run length encoding
void encode(char *s)
{
    char result[1000];  // assuming max size
    int k = 0;
    int n = strlen(s);

    for (int i = 0; i < n; i++) {

        // Count occurrences of current character
        int count = 1;
        while (i < n - 1 && s[i] == s[i + 1]) {
            count++;
            i++;
        }

        // Append character and its count to result
        result[k++] = s[i];

        // convert count to string and append
        char temp[20];
        sprintf(temp, "%d", count);

        for (int j = 0; temp[j] != '\0'; j++) {
            result[k++] = temp[j];
        }
    }

    result[k] = '\0';

    printf("%s", result);
}

// Driver code
int main()
{
    char str[] = "wwwwaaadexxxxxxywww";

    encode(str);

    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to implement run length encoding
    static String encode(String s)
    {
        String result = "";
        int n = s.length();

        for (int i = 0; i < n; i++) {

            // Count occurrences of current character
            int count = 1;
            while (i < n - 1 && s.charAt(i) == s.charAt(i + 1)) {
                count++;
                i++;
            }

            // Append character and its count to result
            result += s.charAt(i);
            result += Integer.toString(count);
        }

        return result;
    }

    public static void main(String[] args)
    {
        String str = "wwwwaaadexxxxxxywww";

        System.out.println(encode(str));
    }
}
Python
# Function to implement run length encoding
def encode(s):
    result = ""
    n = len(s)

    for i in range(n):

        # Count occurrences of current character
        count = 1
        while i < n - 1 and s[i] == s[i + 1]:
            count += 1
            i += 1

        # Append character and its count to result
        result += s[i]
        result += str(count)

    return result


# Driver code
str1 = "wwwwaaadexxxxxxywww"

print(encode(str1))
C#
using System;

class GFG {

    // Function to implement run length encoding
    static string encode(string s)
    {
        string result = "";
        int n = s.Length;

        for (int i = 0; i < n; i++) {

            // Count occurrences of current character
            int count = 1;
            while (i < n - 1 && s[i] == s[i + 1]) {
                count++;
                i++;
            }

            // Append character and its count to result
            result += s[i];
            result += count.ToString();
        }

        return result;
    }

    public static void Main()
    {
        string str = "wwwwaaadexxxxxxywww";

        Console.WriteLine(encode(str));
    }
}
JavaScript
// Function to implement run length encoding
function encode(s)
{
    let result = "";
    let n = s.length;

    for (let i = 0; i < n; i++) {

        // Count occurrences of current character
        let count = 1;
        while (i < n - 1 && s[i] === s[i + 1]) {
            count++;
            i++;
        }

        // Append character and its count to result
        result += s[i];
        result += count.toString();
    }

    return result;
}

// Driver code
let str = "wwwwaaadexxxxxxywww";

console.log(encode(str));

Output
w4a3d1e1x6y1w3
Comment