PrepStack · Markdown HTML

Quickselect order statistic

Divide and conquer · HTML

Formal shape

Convert the request to zero-based ascending target. After partition(lo,hi), pivot rests at p with values <= pivot on the left and > pivot on the right. Return at p=target; otherwise discard the opposite side permanently.

Recognition signals

False friends

SignalWhy it is different
An online streamFuture arrivals change ranks; use a bounded heap or two heaps.
A strict worst-case requirementOrdinary Quickselect can take O(n²); choose a heap or deterministic pivot strategy.
Stable complete orderingPartition mutates order and is not stable; sorting is the proper deliverable.

Core invariant

The target rank remains inside current closed interval [lo,hi]. Each partition finalizes the pivot rank, allowing the side without target to be discarded.

State, transition, and processing order

ItemDefinition
StateA mutable array, lo/hi bounds, zero-based target rank, and randomized pivot.
TransitionPartition to p; set lo=p+1 when p<target, hi=p-1 when p>target, and return on equality.
Frontier / orderOne contiguous range that can still contain the rank; unlike Quicksort, the other partition is never processed.

Python skeleton

from random import randrange

def kth_smallest(nums, k):
    if not 1 <= k <= len(nums): raise ValueError('k')
    a, target = list(nums), k - 1
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        q = randrange(lo, hi + 1)
        a[q], a[hi] = a[hi], a[q]
        pivot, p = a[hi], lo
        for i in range(lo, hi):
            if a[i] <= pivot:
                a[p], a[i] = a[i], a[p]; p += 1
        a[p], a[hi] = a[hi], a[p]
        if p == target: return a[p]
        if p < target: lo = p + 1
        else: hi = p - 1

Correctness sketch

  1. Partition leaves every left value <= pivot and every right value > pivot, giving pivot a valid final rank p.
  2. If target<p it cannot lie at p or to the right; the symmetric argument holds for target>p.
  3. The interval strictly shrinks without discarding target, so equality returns the correct order statistic.

Complexity

TimeSpaceParameters
Expected O(n) with random pivots; worst case O(n²)O(1) in-place iterative; the sample copies input in O(n)n is size and k is 1-based; duplicates affect partition balance.

Edge cases

Error patterns

PatternWhy it fails / fix
Rank indexing errorsKth-smallest uses target=k-1; kth-largest uses target=n-k.
Mismatched partition contractFix closed bounds, equality placement, and pivot's final position before shrinking.
Searching both sides like QuicksortOnly one side contains target; processing both loses selection's advantage.
A consistently bad pivotOrdered input can trigger O(n²); randomize or use a robust pivot.

Selection and exclusion rules

RelationTemplateBoundary
specializationDivide, recurse, and combinePartition permits discarding the side without the target rank.
alternativeTop-K bounded heapInput is online, k is small, or mutation is forbidden.
alternativeTwo heaps for streaming medianThe median must stay current after every insertion.

Original micro-example

PartDetail
ResultThe next partition locates 4 without fully ordering the array.
SetupFor readings [8,2,6,4], find the second smallest.
TraceA pivot of 6 lands at p=2; target=1, so only [2,4] remains.

Recall prompts

My notes