Median of Medians 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 this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Median of Medians runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓Runtime is the same as JavaScript -- no selection primitive -- so TypeScript's contribution is the signature.
- ✓Reviewers reject <T extends number | string> plus a raw a[i] < a[j] -- not because it fails to compile (it compiles fine: TypeScript rejects a relational operator only when the two operand types are mutually non-comparable, like string < number), but because it silently type-checks while mixing a string-ordered and a number-ordered array under one instantiation, and because the union blocks any later specialisation.
- ✓The TypeScript trap: Turn on noUncheckedIndexedAccess and every a[i] becomes T | undefined, so cmp(a[j], pv) stops compiling.
- ✓Types cost nothing at runtime, but the emitted shape decides V8's behaviour. A generic select<T> with a closure comparator stays polymorphic across instantiations and never inlines; a number-specialised copy compiled from the same source (or a Float64Array overload) is what actually runs fast.
What Median of Medians actually is
Median of Medians in TypeScript: what you actually reach for
TypeScript implementation
export type Comparator<T> = (a: T, b: T) => number;
function ins<T>(a: T[], lo: number, hi: number, cmp: Comparator<T>): void {
for (let i = lo + 1; i < hi; i++) {
const v = a[i] as T;
let j = i - 1;
while (j >= lo && cmp(a[j] as T, v) > 0) { a[j + 1] = a[j] as T; j--; }
a[j + 1] = v;
}
}
function pivot<T>(a: T[], lo: number, hi: number, cmp: Comparator<T>): number {
const n = hi - lo;
if (n <= 5) { ins(a, lo, hi, cmp); return lo + (n >> 1); }
let m = lo;
for (let g = lo; g < hi; g += 5) {
const e = Math.min(g + 5, hi);
ins(a, g, e, cmp);
const mid = g + ((e - g) >> 1);
const t = a[m] as T; a[m] = a[mid] as T; a[mid] = t;
m++;
}
return selectNth(a, lo, m, lo + ((m - lo) >> 1), cmp);
}
export function selectNth<T>(a: T[], lo: number, hi: number, k: number, cmp: Comparator<T>): number {
while (hi - lo > 1) {
const p = pivot(a, lo, hi, cmp);
let t = a[lo] as T; a[lo] = a[p] as T; a[p] = t;
const pv = a[lo] as T;
let i = lo;
for (let j = lo + 1; j < hi; j++) {
if (cmp(a[j] as T, pv) < 0) { i++; t = a[i] as T; a[i] = a[j] as T; a[j] = t; }
}
t = a[lo] as T; a[lo] = a[i] as T; a[i] = t;
if (k === i) return k;
if (k < i) hi = i; else lo = i + 1;
}
return k;
}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 Median of Medians?
Runtime is the same as JavaScript -- no selection primitive -- so TypeScript's contribution is the signature. Model the ordering as type Comparator<T> = (a: T, b: T) => number, matching Array.prototype.sort's contract, and declare the buffer as T[] (mutable) rather than readonly T[] so the in-place reorder is visible in the type. The typed-array path needs a separate overload: Float64Array is not assignable to number[], and no shared ArrayLike<number> supertype gives you index assignment, so you either overload or write against a small { length: number; [i: number]: number } shape.
What is the most common TypeScript mistake when implementing Median of Medians?
Turn on noUncheckedIndexedAccess and every a[i] becomes T | undefined, so cmp(a[j], pv) stops compiling. The reflex fix -- a[j]! everywhere -- erases completely at emit, so it does not add a check, it only silences the one flag that would have caught an off-by-one in the partition bounds. Median of medians is exactly where that bites: the group loop writes to a[m] while reading a[g + (e - g >> 1)], and if the last partial group's midpoint is computed from g + 5 instead of e, the read is out of range, yields undefined, and the comparator returns NaN, which compares false in both directions and silently corrupts the pivot rank.
How does Median of Medians actually perform in TypeScript?
Types cost nothing at runtime, but the emitted shape decides V8's behaviour. A generic select<T> with a closure comparator stays polymorphic across instantiations and never inlines; a number-specialised copy compiled from the same source (or a Float64Array overload) is what actually runs fast. Targeting ES5 without downlevelIteration rewrites for...of into an index loop, but WITH it every iteration allocates an iterator result object -- use a plain for loop in the partition. const enum and type-only imports vanish; tuple-destructuring swaps [a[i], a[j]] = [a[j], a[i]] allocate an array per swap unless the target is modern enough to elide it -- prefer a temp. 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 trialBefore paying for Replit, check its student and free-tier options on Noizz.
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.