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

Run-Length Encoding Implementation in TypeScript

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 your String Algorithms question into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Run-Length Encoding runs in O(n) time and O(n) space, in TypeScript as in every other language.
  • ✓TypeScript ships no runtime library at all; what it contributes is the lib.*.d.ts typings that gate which JavaScript API you are allowed to call.
  • ✓Reviewers reject string as the type of a single character: it admits "ab", and nothing stops you constructing the run ["ab", 3].
  • ✓The TypeScript trap: By default TypeScript types every regex capture group as string, never string | undefined (RegExpMatchArray extends Array<string>), so with /(.)(\d+)?/ the decoder's const digits = m[2] is typed string while the runtime value for a non-participating optional group is undefined.
  • ✓Everything above erases; the runtime is exactly the JavaScript page's. TypeScript's cost lands at compile time and in the data shapes it nudges you toward.

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 TypeScript: what you actually reach for

TypeScript ships no runtime library at all; what it contributes is the lib.*.d.ts typings that gate which JavaScript API you are allowed to call. String.prototype.matchAll requires "lib" to include es2020 or later, and Array.prototype.at requires es2022. matchAll throws at runtime on a non-global regex, which the type signature does not model. Model a run as a named tuple, type Run = readonly [ch: string, count: number], or as { readonly ch: string; readonly count: number }: the element names survive into hover text and into error messages.

TypeScript implementation

Reviewers reject string as the type of a single character: it admits "ab", and nothing stops you constructing the run ["ab", 3]. They want a branded alias, type Char = string & { readonly __char: unique symbol }, with one validating constructor, or an opaque Run type that only your tokenizer can mint. They require noUncheckedIndexedAccess on any decoder that indexes, and they will block a non-null assertion m[1]! used to silence the resulting string | undefined instead of handling it.
typescript
type Run = readonly [ch: string, count: number];

export function toRuns(s: string): Run[] {
  const runs: Run[] = [];
  for (const ch of s) {                 // for..of walks code points
    const last = runs.at(-1);           // Run | undefined, always
    if (last !== undefined && last[0] === ch) {
      runs[runs.length - 1] = [ch, last[1] + 1];
    } else {
      runs.push([ch, 1]);
    }
  }
  return runs;
}

export const encode = (s: string): string =>
  toRuns(s).map(([ch, n]) => (n === 1 ? ch : `${ch}${n}`)).join("");

export function decode(s: string): string {
  let out = "";
  for (const m of s.matchAll(/(.)(\d+)?/gsu)) {
    const ch = m[1];
    if (ch === undefined) continue;   // noUncheckedIndexedAccess forces this
    const digits = m[2];              // string | undefined WITH the flag; string WITHOUT it
    out += ch.repeat(digits === undefined ? 1 : Number(digits));
  }
  return out;
}

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 TypeScript-specific trap

By default TypeScript types every regex capture group as string, never string | undefined (RegExpMatchArray extends Array<string>), so with /(.)(\d+)?/ the decoder's const digits = m[2] is typed string while the runtime value for a non-participating optional group is undefined. Number(undefined) is NaN, "x".repeat(NaN) returns "" because the count is coerced to 0, and the run silently disappears; the compiler certified the bug on its way through. The fix is noUncheckedIndexedAccess: its index signature [n: number]: string is exactly what that flag widens, so m[1] and m[2] become string | undefined and you are forced to handle the missing group. m[0] stays string, because lib.es5.d.ts declares 0: string on RegExpMatchArray.

Performance in TypeScript, beyond the O(n)

Everything above erases; the runtime is exactly the JavaScript page's. TypeScript's cost lands at compile time and in the data shapes it nudges you toward. A readonly [string, number] run is a heap-allocated JS array per run; two parallel arrays (string[] plus a Uint32Array or number[] of counts) allocate far less and keep the count numeric; a single flat alternating string[] allocates least of all but stringifies the count, so you trade the tuple's type safety for it. A type-level RLE written as a recursive conditional over a template literal type burns seconds of tsc time and then fails with TS2589 once the literal passes the compiler's instantiation-depth cap. 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 TypeScript specifically, frameworks like React, Express, and Next.js implement related concepts. 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 TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

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

TypeScript ships no runtime library at all; what it contributes is the lib.*.d.ts typings that gate which JavaScript API you are allowed to call. String.prototype.matchAll requires "lib" to include es2020 or later, and Array.prototype.at requires es2022. matchAll throws at runtime on a non-global regex, which the type signature does not model. Model a run as a named tuple, type Run = readonly [ch: string, count: number], or as { readonly ch: string; readonly count: number }: the element names survive into hover text and into error messages.

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

By default TypeScript types every regex capture group as string, never string | undefined (RegExpMatchArray extends Array<string>), so with /(.)(\d+)?/ the decoder's const digits = m[2] is typed string while the runtime value for a non-participating optional group is undefined. Number(undefined) is NaN, "x".repeat(NaN) returns "" because the count is coerced to 0, and the run silently disappears; the compiler certified the bug on its way through. The fix is noUncheckedIndexedAccess: its index signature [n: number]: string is exactly what that flag widens, so m[1] and m[2] become string | undefined and you are forced to handle the missing group. m[0] stays string, because lib.es5.d.ts declares 0: string on RegExpMatchArray.

How does Run-Length Encoding actually perform in TypeScript?

Everything above erases; the runtime is exactly the JavaScript page's. TypeScript's cost lands at compile time and in the data shapes it nudges you toward. A readonly [string, number] run is a heap-allocated JS array per run; two parallel arrays (string[] plus a Uint32Array or number[] of counts) allocate far less and keep the count numeric; a single flat alternating string[] allocates least of all but stringifies the count, so you trade the tuple's type safety for it. A type-level RLE written as a recursive conditional over a template literal type burns seconds of tsc time and then fails with TS2589 once the literal passes the compiler's instantiation-depth cap. 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

Studying for this? Student discounts on developer tools are collected on Noizz, tool by tool.

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.