How it works
Run-length encoding stores a value together with the length of each consecutive run. It does not count all equal values across the whole input; separated runs remain separate. The loop tracks the current character and its count, flushes a run when a different character arrives, and flushes the final run after iteration ends. Forgetting that final flush is a common boundary error.
Empty input needs its own result before reading the first character. This example is an educational representation, not a complete compression format: a reversible format must define how literal digits, separators, and arbitrary characters are encoded.
Test empty text, a single character, and alternating characters. Explain why a decoder cannot safely interpret every possible input until the representation defines escaping and separators.
A working example
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
Console.WriteLine(Encode("aaabbcaa"));
string Encode(string text)
{
if (text.Length == 0) return "";
var result = new StringBuilder(); var current = text[0]; var count = 1;
for (var i = 1; i < text.Length; i++)
{
if (text[i] == current) count++;
else { result.Append(current).Append(count); current = text[i]; count = 1; }
}
return result.Append(current).Append(count).ToString();
}
Expected output
a3b2c1a2
Flush both on a value change and after the final input element.