beginner · strings · two pointers · string builder

Run-length encode a word

Problem

Encode a lowercase word by replacing each run of equal letters with the letter followed by the run's length. For example "aaabcc" becomes "a3b1c2".

Constraints

  • 0 ≤ length ≤ 32
  • letters a–z

Examples

"aaabcc" → "a3b1c2"

"abc" → "a1b1c1"

Show the solution

Scan runs with two pointers

i marks the start of a run; j advances to its end; emit the letter and j − i, then jump i to j.

Why it is correct

Each iteration consumes exactly one maximal run, in order, and emits its encoding.

Complexity

Time O(n), extra space O(n) for the output. j visits each character once overall; appends are amortized O(1) with a builder.

Edge cases

  • Empty word: empty output.
  • Runs longer than 9 produce multi-digit counts.

Common mistakes

  • Building the output with + in a loop (O(n²) copying).
  • Forgetting to emit the last run.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class StringCompression
{
    /// <summary>Run-length encoding: each run of a letter becomes the letter and the run length ("aaab" -> "a3b1"). O(n).</summary>
    public static string Encode(string word)
    {
        var output = new System.Text.StringBuilder();
        int i = 0;
        while (i < word.Length)
        {
            int j = i;
            while (j < word.Length && word[j] == word[i])
                j++;
            output.Append(word[i]).Append(j - i);
            i = j;
        }
        return output.ToString();
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/StringCompression.cs

def encode(word: str) -> str:
    """Run-length encoding: each run of a letter becomes the letter and the run length ("aaab" -> "a3b1"). O(n)."""
    parts: list[str] = []  # joined once at the end: repeated += on strings can be quadratic
    i = 0
    while i < len(word):
        j = i
        while j < len(word) and word[j] == word[i]:
            j += 1
        parts.append(f"{word[i]}{j - i}")
        i = j
    return "".join(parts)

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/string_compression.py

package dev.bekadan.dsa.problems;
 
public final class StringCompression {
    private StringCompression() {
    }
 
    /** Run-length encoding: each run of a letter becomes the letter and the run length ("aaab" -&gt; "a3b1"). O(n). */
    public static String encode(String word) {
        StringBuilder output = new StringBuilder();
        int i = 0;
        while (i < word.length()) {
            int j = i;
            while (j < word.length() && word.charAt(j) == word.charAt(i)) {
                j++;
            }
            output.append(word.charAt(i)).append(j - i);
            i = j;
        }
        return output.toString();
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/StringCompression.java

#pragma once
 
#include <cstddef>
#include <string>
#include <string_view>
 
namespace bekadan::dsa::problems {
 
// Run-length encoding: each run of a letter becomes the letter and the run length ("aaab" -> "a3b1"). O(n).
inline std::string string_compression(std::string_view word) {
    std::string output;  // std::string::append is amortized O(1): strings are mutable in C++
    std::size_t i = 0;
    while (i < word.size()) {
        std::size_t j = i;
        while (j < word.size() && word[j] == word[i])
            ++j;
        output += word[i];
        output += std::to_string(j - i);
        i = j;
    }
    return output;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/string_compression.hpp