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

Median of Medians Implementation in Python

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 Python as in every other language.
  • ✓CPython ships no nth_element. statistics.median_low(g) (import statistics) gives you an ELEMENT of the group rather than an average, which is what a pivot must be; for groups of five sorted(g)[2] is cheaper.
  • ✓Reviewers insist the recursion carries (lo, hi) index bounds into ONE list and never a slice, because a[lo:hi] copies.
  • ✓The Python trap: statistics.median averages the two middle values on an even-length group, so it can return a number that is NOT in the array -- and for ints it returns a float.
  • ✓Every comparison is a PyObject_RichCompare dispatch through the interpreter loop, so the constant factor is roughly 50-100x C.

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

CPython ships no nth_element. statistics.median_low(g) (import statistics) gives you an ELEMENT of the group rather than an average, which is what a pivot must be; for groups of five sorted(g)[2] is cheaper. heapq.nsmallest(k, it) covers tiny k in O(n log k). numpy.partition / numpy.argpartition (import numpy) do the real job in C using introselect: a median-of-3 quickselect that falls back to median-of-medians-of-5 once the recursion budget is spent, so the worst case is O(n), not merely expected O(n). Write BFPRT yourself when you cannot take a NumPy dependency, when the data is not a dense numeric array, or to teach it -- not because NumPy's bound is weaker.

Python implementation

Reviewers insist the recursion carries (lo, hi) index bounds into ONE list and never a slice, because a[lo:hi] copies. They want range(lo, hi, 5) for grouping instead of building chunk lists, list.__setitem__ swaps via the a[i], a[j] = a[j], a[i] tuple form, and the outer quickselect written as a while loop that narrows lo/hi rather than a tail call. Passing key= instead of a raw comparator matches sorted/min/max and gets accepted; a custom cmp does not.
python
def _ins(a, lo, hi):
    for i in range(lo + 1, hi):
        v = a[i]; j = i - 1
        while j >= lo and a[j] > v:
            a[j + 1] = a[j]; j -= 1
        a[j + 1] = v

def _pivot(a, lo, hi):
    n = hi - lo
    if n <= 5:
        _ins(a, lo, hi)
        return lo + n // 2
    m = lo
    for g in range(lo, hi, 5):
        e = min(g + 5, hi)
        _ins(a, g, e)
        mid = g + (e - g) // 2
        a[m], a[mid] = a[mid], a[m]
        m += 1
    return _select(a, lo, m, lo + (m - lo) // 2)

def _select(a, lo, hi, k):
    while hi - lo > 1:
        p = _pivot(a, lo, hi)
        a[lo], a[p] = a[p], a[lo]
        pv = a[lo]; i = lo
        for j in range(lo + 1, hi):
            if a[j] < pv:
                i += 1
                a[i], a[j] = a[j], a[i]
        a[lo], a[i] = a[i], a[lo]
        if k == i:
            return k
        if k < i:
            hi = i
        else:
            lo = i + 1
    return k

def select_kth(a, k):
    return a[_select(a, 0, len(a), 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 Python-specific trap

statistics.median averages the two middle values on an even-length group, so it can return a number that is NOT in the array -- and for ints it returns a float. Use it as your pivot and two things break, both of them Python-specific. For large ints the averaging itself blows up before any comparison happens: statistics.median([10**400, 10**400 + 2]) raises OverflowError: integer division result too large for a float (verified). Below that ceiling you get a float pivot that is exact-compared against your ints -- CPython 3 compares int against float exactly, so 2**53 + 1 == float(2**53) is correctly False -- so the mixed comparison is the one thing that does NOT lie. The damage is the pivot itself: it is a value that is not in the array, so you can no longer locate its final index by identity and 'return a[k]' has nothing to anchor to. Use statistics.median_low, or index the sorted group.

Performance in Python, beyond the O(n)

Every comparison is a PyObject_RichCompare dispatch through the interpreter loop, so the constant factor is roughly 50-100x C. list.sort() (Timsort, C-level compares on the whole array) beats a pure-Python O(n) BFPRT at every size you will ever run: measured 9.1x faster at 10^4, 7.3x at 10^5, 6.1x at 10^6. The interpreter constant is so large that the O(n) vs O(n log n) gap closes only as log n, which never happens in practice -- so pure-Python BFPRT is for the worst-case GUARANTEE, never for speed. When you want speed, use list.sort() below ~10^5 and numpy.partition above it. The 5-element group sorts dominate: prefer an inlined insertion loop over calling sorted() n/5 times, which allocates a new list each call. Recursion depth is O(log n), so sys.setrecursionlimit is not the issue -- slice copies are. 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 Python, 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 Python, demonstrate proficiency with list comprehensions and generator expressions to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Python code that is both correct and maintainable.

Frequently Asked Questions

Which Python type or library should I use for Median of Medians?

CPython ships no nth_element. statistics.median_low(g) (import statistics) gives you an ELEMENT of the group rather than an average, which is what a pivot must be; for groups of five sorted(g)[2] is cheaper. heapq.nsmallest(k, it) covers tiny k in O(n log k). numpy.partition / numpy.argpartition (import numpy) do the real job in C using introselect: a median-of-3 quickselect that falls back to median-of-medians-of-5 once the recursion budget is spent, so the worst case is O(n), not merely expected O(n). Write BFPRT yourself when you cannot take a NumPy dependency, when the data is not a dense numeric array, or to teach it -- not because NumPy's bound is weaker.

What is the most common Python mistake when implementing Median of Medians?

statistics.median averages the two middle values on an even-length group, so it can return a number that is NOT in the array -- and for ints it returns a float. Use it as your pivot and two things break, both of them Python-specific. For large ints the averaging itself blows up before any comparison happens: statistics.median([10**400, 10**400 + 2]) raises OverflowError: integer division result too large for a float (verified). Below that ceiling you get a float pivot that is exact-compared against your ints -- CPython 3 compares int against float exactly, so 2**53 + 1 == float(2**53) is correctly False -- so the mixed comparison is the one thing that does NOT lie. The damage is the pivot itself: it is a value that is not in the array, so you can no longer locate its final index by identity and 'return a[k]' has nothing to anchor to. Use statistics.median_low, or index the sorted group.

How does Median of Medians actually perform in Python?

Every comparison is a PyObject_RichCompare dispatch through the interpreter loop, so the constant factor is roughly 50-100x C. list.sort() (Timsort, C-level compares on the whole array) beats a pure-Python O(n) BFPRT at every size you will ever run: measured 9.1x faster at 10^4, 7.3x at 10^5, 6.1x at 10^6. The interpreter constant is so large that the O(n) vs O(n log n) gap closes only as log n, which never happens in practice -- so pure-Python BFPRT is for the worst-case GUARANTEE, never for speed. When you want speed, use list.sort() below ~10^5 and numpy.partition above it. The 5-element group sorts dominate: prefer an inlined insertion loop over calling sorted() n/5 times, which allocates a new list each call. Recursion depth is O(log n), so sys.setrecursionlimit is not the issue -- slice copies are. 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? Replit free tiers and academic plans are laid out 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.