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

Median of Medians Implementation in TypeScript

19 min readadvanced
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

  • ✓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 (BFPRT) is the pivot rule that makes quickselect linear in the WORST case, not just on average. Split the array into groups of five, sort each group, take each group's median, recursively select the median of those medians, and partition on it. That pivot is guaranteed to have at least ~30% of elements on each side, so T(n) = T(n/5) + T(7n/10) + O(n) = O(n). That bound assumes DISTINCT keys. With a two-way partition on strict <, an input of many equal keys puts every equal element on the greater side, so the range shrinks by exactly one element per step and the whole thing goes quadratic or worse -- the opposite of what you came for, on the cheapest input an attacker can send. Production BFPRT partitions three ways (< pivot / == pivot / > pivot, the Dutch-national-flag split) and returns immediately when k falls inside the equal band. Every snippet below shows the two-way core for clarity; swap in a three-way partition before you rely on the worst-case bound. You reach for it when a random pivot is unacceptable: adversarial or attacker-supplied input, a hard real-time deadline, or a provable bound you have to defend in review.

Median of Medians in TypeScript: what you actually reach for

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.

TypeScript implementation

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. Pass an explicit Comparator<T>. They also reject a return type of T when the function actually mutates: return the INDEX and let the caller read a[k], or document the mutation in the signature name (selectNthInPlace). Sprinkled non-null assertions get flagged; so does declaring the parameter readonly T[] and then writing to it via a cast.
typescript
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 Free

The TypeScript-specific trap

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.

Performance in TypeScript, beyond the O(n)

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. 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 Median of Medians between languages.

Real-World Applications

Median of Medians applies wherever its problem shape appears in your own code. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Median of Medians helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Median of Medians appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Median of Medians 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 Median of Medians 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 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).

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

Before paying for Replit, check its student and free-tier options 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

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.