Run-Length Encoding Implementation in TypeScript
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 in TypeScript: what you actually reach for
TypeScript implementation
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 FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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 trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.