Run-length encode a string
Compress consecutive runs of the same character by writing the character followed by its run length.
Course progress
Problem 38 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "aaabbccccdaa"
Expected output
a3b2c4d1a2
What is happening?
The consecutive runs are aaa, bb, cccc, d, and aa. Writing each character with its run length gives a3b2c4d1a2.
Solution strategy
Build the right mental model
Track the current run length while scanning. When the character changes, append the completed run and start counting the new one.
Core concepts
strings · compression
Complexity
Time O(n), space O(n) for the encoded result.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for run-length-encoding
using System;
using System.Text;
class Program
{
static string Encode(string text)
{
if (text.Length == 0) return "";
var encoded = new StringBuilder();
int runLength = 1;
for (int i = 1; i <= text.Length; i++)
{
if (i < text.Length && text[i] == text[i - 1])
{
runLength++;
continue;
}
encoded.Append(text[i - 1]);
encoded.Append(runLength);
runLength = 1;
}
return encoded.ToString();
}
static void Main()
{
Console.WriteLine(Encode("aaabbccccdaa"));
}
}Knowledge check
Questions students often ask
What is the main idea behind run-length encode a string?
Track the current run length while scanning. When the character changes, append the completed run and start counting the new one.
What is the time and space complexity of this solution?
Time O(n), space O(n) for the encoded result.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.