← Questions

Median of a large unsorted array in linear time

0

A coding interview question asked at Google, Meta and Airbnb. It tests quickselect, selection and partitioning.

You are given a very large, unsorted list of integers nums. Return its median.

  • If len(nums) is odd, the median is the middle value once the list is sorted.
  • If len(nums) is even, the median is the average of the two middle values once the list is sorted.

Implement find_median(nums: list[int]) -> float.

Sorting the whole list is too slow for the data sizes we care about. Your solution must run in expected (average) O(n) time.

Constraints

  • 1 <= len(nums) <= 10^7
  • -10^9 <= nums[i] <= 10^9
  • Values may repeat, and the list may contain long runs of the same value.
  • Do not change the caller's list unless you say so and explain the trade-off.

Example 1

nums = [9, 2, 7, 4, 5]
Output: 5.0

Sorted, the list is [2, 4, 5, 7, 9]. The middle value is 5.

Example 2

nums = [8, 3, 3, 12, 1, 6]
Output: 4.5

Sorted, the list is [1, 3, 3, 6, 8, 12]. The two middle values are 3 and 6, and their average is 4.5.

Clarifying questions

  • Is returning a float fine even when the median is a whole number (5.0)?
  • May I copy the list (10^7 integers is significant memory), or must I select in place?
  • Is expected O(n) enough, or is a worst-case O(n) guarantee required?

What a strong answer covers

  • Uses quickselect with a random pivot to find the k-th smallest in expected O(n).
  • Partitions three ways (less, equal, greater) so long runs of one value do not degrade it to O(n^2).
  • For an even length, selects the lower middle, then takes the minimum of the part to its right for the upper middle, instead of a second full select.
  • Implements it iteratively, and states the copy-versus-in-place trade-off (in place mutates the caller's list; a copy doubles memory).
  • Mentions median of medians for a worst-case O(n) guarantee, and its larger constant.
  • Tests odd and even lengths, all equal values, one element, and a check against sorted on random lists.

Follow-ups

  • The numbers arrive as a stream: keep a running median with two heaps.
  • The data does not fit in memory: bucket or binary-search on the value range with counting passes.
  • Find the k-th smallest, or several percentiles at once.

Where it's asked

What it tests

quickselect · selection · partitioning · heap

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding