Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Run-Length Encoding Implementation in C#

11 min readbeginner
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Run-Length Encoding runs in O(n) time and O(n) space, in C# as in every other language.
  • ✓System.Text.StringBuilder is the accumulator, and its Append(char value, int repeatCount) overload is exactly a decoded run in one call.
  • ✓Reviewers want ReadOnlySpan<char> on the read side and StringBuilder or string.Create on the write side, never s += part.
  • ✓The C# trap: Span<char> and ReadOnlySpan<char> are ref structs: stack-only, so they cannot be a field of a class, cannot survive an await, and cannot exist inside an iterator method.
  • ✓StringBuilder is a linked list of char chunks, so growth never re-copies what is already written, but ToString() must walk every chunk and copy into one final array; for a known output length string.Create skips that second pass entirely.

What Run-Length Encoding actually is

Run-length encoding replaces each maximal run of identical adjacent symbols with the symbol plus its repeat count: aaabbc becomes a3b2c. One left-to-right pass with a single symbol of lookahead, no dictionary, no sliding window, no back-references. Engineers reach for it where the data is already run-heavy: 1-bit fax and bitmap scanlines, PCX/BMP/TGA sprite masks, sparse column masks, and as the cheap final stage after a transform that manufactures runs, such as move-to-front output after Burrows-Wheeler. On random text it inflates, so the format almost always needs an escape or a literal-block mode.

Run-Length Encoding in C#: what you actually reach for

System.Text.StringBuilder is the accumulator, and its Append(char value, int repeatCount) overload is exactly a decoded run in one call. ReadOnlySpan<char> from System lets the encoder read a slice of the input with no allocation. System.Text.Rune models a full Unicode scalar, and string.EnumerateRunes() returns a StringRuneEnumerator over them; that is what you want instead of foreach (char c in s), which walks UTF-16 units. string.Create<TState>(int length, TState state, SpanAction<char, TState> action) writes the final string in place when the output length is known up front.

C# implementation

Reviewers want ReadOnlySpan<char> on the read side and StringBuilder or string.Create on the write side, never s += part. They want the char-versus-Rune choice stated explicitly in the signature or the doc comment. They reject Append(n.ToString()) in favour of Append(n), which formats directly into the builder's span with no intermediate string, and reject Append(someObject) because that boxes. Public API is static, carries an XML doc comment, and validates reference parameters with ArgumentNullException.ThrowIfNull.
csharp
using System;
using System.Text;

public static class Rle
{
    /// <summary>Run-length encodes s, counting UTF-16 code units.</summary>
    public static string Encode(ReadOnlySpan<char> s)
    {
        var sb = new StringBuilder(s.Length);
        int i = 0;
        while (i < s.Length)
        {
            char c = s[i];
            int n = 1;
            while (i + n < s.Length && s[i + n] == c) n++;
            sb.Append(c);
            if (n > 1) sb.Append(n);   // formats in place, no ToString()
            i += n;
        }
        return sb.ToString();
    }

    public static string Decode(ReadOnlySpan<char> s)
    {
        var sb = new StringBuilder(s.Length * 2);
        int i = 0;
        while (i < s.Length)
        {
            char c = s[i++];
            int n = 0;
            while (i < s.Length && s[i] is >= '0' and <= '9')
                n = n * 10 + (s[i++] - '0');
            sb.Append(c, n == 0 ? 1 : n);
        }
        return sb.ToString();
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The C#-specific trap

Span<char> and ReadOnlySpan<char> are ref structs: stack-only, so they cannot be a field of a class, cannot survive an await, and cannot exist inside an iterator method. The obvious streaming API (static IEnumerable<(char Ch, int Count)> Runs(ReadOnlySpan<char> s) with yield return) simply does not compile, and the compiler error points at the iterator rather than at the span. You either materialise a List<(char, int)> and surrender the whole allocation win, or hand-write a ref struct enumerator exposing GetEnumerator, MoveNext and Current for foreach to duck-type onto.

Performance in C#, beyond the O(n)

StringBuilder is a linked list of char chunks, so growth never re-copies what is already written, but ToString() must walk every chunk and copy into one final array; for a known output length string.Create skips that second pass entirely. Append(int) formats through int.TryFormat straight into the chunk's span. The JIT hoists the bounds check on s[i] for a canonical for (i = 0; i < s.Length; i++) but usually not for an i + n < s.Length probe; the Encode above is written with exactly that probe for compactness, so its inner scan keeps its bounds check, and a monotone cursor (int j = i + 1; while (j < s.Length && s[j] == c) j++; int n = j - i;) is the shape that lets the check hoist. Spans behave the same. Tiered compilation runs the first thousands of iterations unoptimised until on-stack replacement kicks in. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Run-Length Encoding between languages.

Real-World Applications

Run-Length Encoding is used extensively in production software: database engines, compilers, operating systems, and application frameworks all use Run-Length Encoding internally. In C# specifically, .NET, Entity Framework, and ASP.NET Core use these patterns. Understanding Run-Length Encoding helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Run-Length Encoding appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Run-Length Encoding over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Run-Length Encoding to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

Frequently Asked Questions

Which C# type or library should I use for Run-Length Encoding?

System.Text.StringBuilder is the accumulator, and its Append(char value, int repeatCount) overload is exactly a decoded run in one call. ReadOnlySpan<char> from System lets the encoder read a slice of the input with no allocation. System.Text.Rune models a full Unicode scalar, and string.EnumerateRunes() returns a StringRuneEnumerator over them; that is what you want instead of foreach (char c in s), which walks UTF-16 units. string.Create<TState>(int length, TState state, SpanAction<char, TState> action) writes the final string in place when the output length is known up front.

What is the most common C# mistake when implementing Run-Length Encoding?

Span<char> and ReadOnlySpan<char> are ref structs: stack-only, so they cannot be a field of a class, cannot survive an await, and cannot exist inside an iterator method. The obvious streaming API (static IEnumerable<(char Ch, int Count)> Runs(ReadOnlySpan<char> s) with yield return) simply does not compile, and the compiler error points at the iterator rather than at the span. You either materialise a List<(char, int)> and surrender the whole allocation win, or hand-write a ref struct enumerator exposing GetEnumerator, MoveNext and Current for foreach to duck-type onto.

How does Run-Length Encoding actually perform in C#?

StringBuilder is a linked list of char chunks, so growth never re-copies what is already written, but ToString() must walk every chunk and copy into one final array; for a known output length string.Create skips that second pass entirely. Append(int) formats through int.TryFormat straight into the chunk's span. The JIT hoists the bounds check on s[i] for a canonical for (i = 0; i < s.Length; i++) but usually not for an i + n < s.Length probe; the Encode above is written with exactly that probe for compactness, so its inner scan keeps its bounds check, and a monotone cursor (int j = i + 1; while (j < s.Length && s[j] == c) j++; int n = j - i;) is the shape that lets the check hoist. Spans behave the same. Tiered compilation runs the first thousands of iterations unoptimised until on-stack replacement kicks in. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what GitHub Copilot offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.