We are given a list of integers. We need to find the median. The median is the middle value when the list is sorted.
If the list has an odd number of elements, the median is the middle element.
If the list has an even number of elements, the median is the average of the two middle elements.
However, the problem asks:
- Write a function that solves this problem.
- Explain the algorithm.
- What is the time complexity if you sort the list first?
- Can you do better? (Hint: using a selection algorithm like Quickselect)
Let's address each part:
-
Function to find the median:
We can do it by sorting and then picking the middle element(s). But the hint suggests using Quickselect for better complexity.
-
Algorithm explanation:
a. Sorting approach: sort the list and then pick the median. This is O(n log n) time.
b. Quickselect approach: we can use Quickselect to find the kth smallest element. For median:
- If n is odd: k = n//2 (0-indexed) or (n+1)//2 (1-indexed). We want the element at index (n//2) in 0-indexed after sorting.
- If n is even: we need the two middle elements, at indices (n//2 - 1) and (n//2) in 0-indexed, then average them.
Quickselect has average O(n) time but worst-case O(n^2). However, we can use median-of-medians to make it O(n) worst-case, but that is more complex.
-
Time complexity if we sort: O(n log n).
-
Can we do better? Yes, with Quickselect we can achieve average O(n) time.
However, note that for even n we need two elements. We can do two Quickselects: one for the lower median and one for the upper median, but that would be 2*O(n) on average, still O(n).
Alternatively, we can use a selection algorithm that returns both the kth and (k+1)th smallest? But typically Quickselect returns one.
But note: we can run Quickselect for the (n//2)th smallest (0-indexed) and then for the (n//2-1)th smallest? Actually for even n, we need the (n//2-1)th and (n//2)th (0-indexed). We can do:
If n is odd:
median = quickselect(arr, n//2)
If n is even:
m1 = quickselect(arr, n//2 - 1)
m2 = quickselect(arr, n//2) # but note: after the first quickselect, the array is partially partitioned? We have to be careful.
However, the standard Quickselect modifies the array. So if we run it twice, the second run might not have the same state. We can either:
- Make a copy of the array for the second run? That would be O(n) extra space and still O(n) time.
- Or we can run Quickselect for the (n//2)th and then in the left part (which is <= pivot) we can find the maximum? Actually, after the first Quickselect for the (n//2)th, the element at index (n//2) is in place, and all elements to the left are <= it. But we don't know if the (n//2-1)th is the maximum of the left part? Not necessarily, because the left part is not sorted.
Alternatively, we can run Quickselect for the (n//2)th and then run a second Quickselect on the left part (from 0 to n//2-1) to find the maximum? But that would be O(n) again? Actually, the left part has size n//2, so the second Quickselect would be O(n/2) on average? But then we have to be careful: we want the (n//2-1)th smallest in the entire array, which is the maximum of the first n//2 elements? Not exactly: because after the first Quickselect, the first n//2 elements are the smallest n//2 elements, but they are not sorted. So the (n//2-1)th smallest is the largest among these n//2? Yes, because the n//2 smallest elements are in the first n//2 positions (but unsorted). So we can find the maximum of the first n//2 elements in O(n) time? That would be O(n/2) which is O(n). But then we have two O(n) operations? Actually, the first Quickselect is O(n) on average, and then finding the maximum in the first n//2 is O(n/2). So total O(n) + O(n/2) = O(1.5n) which is still O(n).
But wait: what if we do it in one pass? There is a way to find both medians in one Quickselect? Not straightforward.
Alternatively, we can use a selection algorithm that returns the kth smallest and also partitions the array such that the left part is the k smallest. Then for even n, we can get the two middle elements by:
Let k = n//2
Quickselect for the kth smallest (0-indexed). Then the kth smallest is in place at index k. Now the array is partitioned such that [0..k-1] are <= arr[k] and [k+1..n-1] are >= arr[k]. But note: the kth smallest is the (k+1)th smallest in 1-indexed? Actually, in 0-indexed, the kth smallest is at index k after partitioning? Not exactly: Quickselect returns the kth smallest and places it at index k? Actually, in the standard Lomuto partition, after partitioning the pivot is at its correct position. So if we are looking for the kth smallest, and we partition around a pivot, then if the pivot index is k, we are done. So after Quickselect, the element at index k is the kth smallest.
Then for even n, we need the (k-1)th smallest as well. The (k-1)th smallest must be in the left part (indices 0 to k-1) and it is the maximum of that left part? Because the left part has k elements (indices 0 to k-1) and they are all <= the kth smallest. And the (k-1)th smallest is the largest among the first k? Not necessarily: the left part is not sorted, so the maximum of the left part is the kth smallest? Actually, the left part contains the k smallest elements, so the maximum of the left part is the kth smallest? Wait, the kth smallest is at index k, which is not in the left part. The left part (0 to k-1) has the smallest k elements? No: the left part has the elements that are <= the pivot (which is the kth smallest). But note: the pivot is the kth smallest, so there are exactly k elements that are <= the pivot? Not necessarily: there could be duplicates. But in the partition, we put all elements <= pivot on the left, and > pivot on the right. So the left part has at least k elements? Actually, the pivot is at index k, so there are exactly k elements to the left (indices 0 to k-1) and they are all <= pivot. And the pivot is the kth smallest, meaning there are k-1 elements smaller than or equal to the pivot? This is getting messy.
Let me clarify: In the standard Quickselect, we are looking for the element that would be at index k if the array were sorted. After partitioning, the pivot is placed at its correct position, say p. Then:
if p == k: we are done.
if p > k: we recurse on the left part (0 to p-1) for the kth smallest.
if p < k: we recurse on the right part (p+1 to n-1) for the (k - (p+1))th smallest? Actually, we adjust k.
So after we find the kth smallest, the array is partitioned such that:
[0..k-1] are <= the kth smallest? Not exactly: because the kth smallest is at index k, and by definition of partitioning, all elements at indices < k are <= the element at k? Actually, in the final partition, the pivot is at index k, and all elements to the left are <= pivot and to the right are >= pivot. But note: there might be duplicates, so some elements equal to the pivot might be on the right? In the standard Lomuto partition, we put elements <= pivot on the left and > on the right. So after the final partition, the element at index k is the kth smallest, and the elements at indices 0 to k-1 are <= the kth smallest, and the elements at indices k+1 to n-1 are >= the kth smallest.
Therefore, the (k-1)th smallest must be in the left part (0 to k-1) and it is the maximum of that left part? Not necessarily: because the left part has k elements (0 to k-1) and they are all <= the kth smallest. The (k-1)th smallest is the second smallest of the k+1 smallest? Actually, the kth smallest is the smallest of the right part? This is confusing.
Alternatively, we can run Quickselect for the (k-1)th smallest first, then for the kth smallest? But after the first run, the array is partitioned for the (k-1)th smallest. Then we run the second Quickselect on the right part? This is getting too complicated.
Given the complexity, for even n, it might be simpler to run two separate Quickselects on two copies of the array? But that would be O(n) space if we copy, and O(n) time on average? Actually, we can run the first Quickselect for the (n//2)th smallest, then we know that the (n//2-1)th smallest is the maximum of the first n//2 elements? Let's think:
Let n be even, and let k = n//2.
We want the kth smallest (0-indexed) and the (k-1)th smallest.
After we find the kth smallest (let's call it x) at index k, we know that the first k elements (0 to k-1) are <= x. But note: the (k-1)th smallest is the largest among the first k elements? Not necessarily, because the first k elements are the k smallest, but they are not sorted. The (k-1)th smallest is the second largest among the first k? Actually, the (k-1)th smallest is the element that would be at index k-1 if the array were sorted. Since the first k elements are the k smallest, the (k-1)th smallest must be in the first k elements, but it is not necessarily the maximum of the first k. For example, consider an array [1,2,3,4] (n=4, k=2). The 2nd smallest (0-indexed) is 3? Wait, 0-indexed: 0th smallest is 1, 1st is 2, 2nd is 3, 3rd is 4. So for n=4, k=2, we want the 2nd smallest (which is 3) and the 1st smallest (which is 2). After Quickselect for the 2nd smallest, we might have the array partitioned as [1,2,3,4] or [2,1,3,4] etc. The first two elements are <=3, but the 1st smallest (2) is not the maximum of the first two? In [2,1,3,4], the first two are [2,1] and the maximum is 2, which is the 1st smallest? Yes, because the 1st smallest is 2. In [1,2,3,4], the first two are [1,2] and the maximum is 2, which is the 1st smallest. So it seems that the (k-1)th smallest is the maximum of the first k elements? Let's test with another example: [1,3,2,4] (n=4). The sorted order is [1,2,3,4]. The 2nd smallest (k=2) is 3. After Quickselect for the 2nd smallest, we might have [1,2,3,4] or [2,1,3,4] or [1,3,2,4]? Actually, when we partition for the 2nd smallest, we want the element at index 2 to be the 2nd smallest. In [1,3,2,4], if we partition with pivot 3 (for example), we might get [1,2,3,4]. Then the first two are [1,2] and the maximum is 2, which is the 1st smallest. So yes, it seems that the (k-1)th smallest is the maximum of the first k elements.
Why? Because the first k elements (0 to k-1) are the k smallest elements in the array. The (k-1)th smallest is the largest among these k smallest? Actually, the k smallest elements are the ones that are <= the kth smallest. And the (k-1)th smallest is the second largest of the k smallest? Wait, the k smallest are: the 0th, 1st, ..., (k-1)th, and kth? No, the k smallest are the 0th to (k-1)th? Actually, the k smallest are the 0th to (k-1)th? That would be k elements. But we have the kth smallest at index k, which is not included in the first k. So the first k elements (0 to k-1) are exactly the k smallest? Yes, because the element at index k is the (k+1)th smallest? Wait, I'm mixing 0-indexed and 1-indexed.
Let me use 0-indexed:
The 0th smallest is the minimum.
The 1st smallest is the second minimum.
...
The (k-1)th smallest is the kth minimum? Actually, the (k-1)th smallest is the element that would be at index k-1 in the sorted array.
After Quickselect for the kth smallest (0-indexed), we have:
arr[0..k-1] <= arr[k] and arr[k+1..n-1] >= arr[k].
And arr[k] is the kth smallest.
Therefore, the first k elements (0 to k-1) are the k smallest? Not exactly: they are all <= the kth smallest, but there might be duplicates. However, by definition of the kth smallest, there are exactly k elements that are <= the kth smallest? Actually, the kth smallest is the element such that there are exactly k elements that are <= it? That is not true if there are duplicates. For example, in [1,1,1,1], the 2nd smallest (0-indexed) is 1, and there are 4 elements <=1. So the condition "exactly k elements <= the kth smallest" is not always true.
But in the Quickselect algorithm, we are finding the element that would be at index k in the sorted array. So if we have duplicates, the element at index k in the sorted array is the kth smallest, and there are at least k+1 elements that are <= it? Actually, in the sorted array, the element at index k is the (k+1)th element in 1-indexed? No, in 0-indexed, the element at index k is the (k+1)th smallest? Wait, let's define:
Sorted array: [a0, a1, ..., a_{n-1}]
a0 is the 0th smallest (minimum).
a1 is the 1st smallest.
...
a_k is the kth smallest.
So in the sorted array, the element at index k is the kth smallest. And note that in the sorted array, all elements at indices 0 to k are <= a_k? Actually, by definition of sorted array, a0 <= a1 <= ... <= a_k. So the first k+1 elements (0 to k) are <= a_k? But a_k is at index k, so the elements at indices 0 to k-1 are <= a_k? Yes, because the array is sorted. But in the partitioned array after Quickselect, we have:
arr[0..k-1] <= arr[k] and arr[k+1..n-1] >= arr[k].
So the first k elements are <= arr[k], but note that arr[k] itself is at index k. So the set of elements that are <= the kth smallest (arr[k]) includes the first k elements and arr[k] itself? That would be k+1 elements? But in the sorted array, the kth smallest (a_k) has exactly k elements that are less than or equal to it? Actually, in the sorted array, the elements at indices 0 to k are all <= a_k? That's k+1 elements. But wait, the kth smallest is a_k, and the elements that are <= a_k are a0, a1, ..., a_k. That's k+1 elements? Because indices 0 to k inclusive is k+1 elements. But the kth smallest is the (k+1)th element in 1-indexed? I'm getting confused.
Let's use 1-indexed for a moment:
The 1st smallest is the minimum.
The 2nd smallest is the next.
...
The kth smallest is the element at position k in the sorted array (1-indexed).
In 0-indexed, the kth smallest is at index k-1? No, in 0-indexed, the 0th smallest is at index 0, the 1st smallest at index 1, etc. So the kth smallest (0-indexed) is at index k.
Therefore, in the sorted array (0-indexed), the element at index k is the kth smallest. And the elements at indices 0 to k-1 are the 0th to (k-1)th smallest. So there are exactly k elements that are less than or equal to the kth smallest? Actually, the elements at indices 0 to k are all <= the kth smallest? That's k+1 elements. But wait, the kth smallest is at index k, and the elements at indices 0 to k-1 are <= it, and the element at index k is equal to itself. So total k+1 elements that are <= the kth smallest? That cannot be, because the kth smallest is defined as the element that has exactly k elements less than or equal to it? Actually, the definition of the kth smallest is: the element that would be at position k in the sorted list (0-indexed). So in the sorted list, there are exactly k elements that are less than or equal to the kth smallest? Let's test:
Sorted list: [1,2,3,4] (n=4)
k=2 (0-indexed): the 2nd smallest is 3. How many elements are <=3? Three: 1,2,3. But k=2, so we have 3 elements <= the 2nd smallest? That doesn't match.
Actually, the kth smallest (0-indexed) is the element that has exactly k elements that are less than or equal to it? In [1,2,3,4], for k=2 (3), there are 3 elements <=3 (1,2,3). So that's k+1.
The correct definition: the kth smallest (0-indexed) is the element such that there are exactly k elements that are strictly less than it? Not necessarily, because of duplicates.
Given the confusion, it's better to stick to the index in the sorted array.
After Quickselect for the kth smallest (0-indexed), we have the element at index k is the kth smallest. And the elements at indices 0 to k-1 are the smallest k elements? Not necessarily: they are all <= the kth smallest, but there might be duplicates of the kth smallest in the left part? In the standard Lomuto partition, we put elements <= pivot on the left. So if there are duplicates of the pivot, they might be on the left? Actually, in the partition step, we swap elements that are <= pivot to the left. So after partition, the pivot is at its correct position, and the left part has elements <= pivot. But note: the pivot might appear multiple times. So the left part may contain some copies of the pivot. Therefore, the first k elements (0 to k-1) are not necessarily the k smallest, because there might be copies of the pivot that are in the left part and also at index k? Actually, the pivot at index k is one instance. So the left part (0 to k-1) are <= pivot, and the pivot at index k is also equal to pivot. So the set of elements that are <= pivot includes the left part and the pivot at index k. But the kth smallest is the pivot, so the left part (0 to k-1) are the smallest k elements? Not exactly: because if there are duplicates, the left part might contain some of the duplicates and the pivot at index k is another duplicate. So the left part has exactly k elements? Yes, indices 0 to k-1 are k elements. And they are all <= the kth smallest. And the kth smallest is at index k. So the first k elements are the k smallest? Not necessarily: because there might be an element equal to the kth smallest that is in the right part? In the partition, we put elements > pivot on the right. So if there is an element equal to the pivot, it would be in the left part? In the standard Lomuto, we use <= for the left. So all elements equal to the pivot are in the left part? Actually, in the partition, we increment the index for elements <= pivot. So when we see an element equal to pivot, we include it in the left part. Therefore, after partition, all elements equal to the pivot are in the left part? Not exactly: the pivot itself is swapped to the position at the end of the left part? Let's recall Lomuto:
pivot = arr[high]
i = low - 1
for j from low to high-1:
if arr[j] <= pivot:
i++
swap arr[i] and arr[j]
swap arr[i+1] and arr[high]
return i+1
So after this, the pivot is at index i+1. And the elements at indices low to i are <= pivot, and the elements at indices i+2 to high are > pivot. So the left part (low to i) are <= pivot, and the pivot is at i+1. So if we are looking for the kth smallest and the pivot ends up at index p (which is i+1), then the left part has p-low elements (which are <= pivot) and the right part has high-p elements (which are > pivot). So the left part does not include the pivot. Therefore, the first p elements (0 to p-1) are <= pivot and the pivot is at p. So the first p elements are the smallest p elements? Not exactly: they are all <= the pivot, but there might be duplicates of the pivot in the left part? Actually, the left part has elements <= pivot, so if there are duplicates of the pivot, they are in the left part. So the left part (0 to p-1) contains elements that are <= pivot, and the pivot at p is also equal to pivot. So the set of elements that are <= pivot includes the left part and the pivot at p. But the left part has p elements (0 to p-1) and the pivot is at p. So total p+1 elements that are <= pivot? But note: the left part might contain duplicates of the pivot, so the count of elements <= pivot is at least p+1? Actually, the left part has p elements that are <= pivot, and the pivot at p is also <= pivot (equal). So there are at least p+1 elements <= pivot. But the pivot is the (p)th smallest? Let's see:
In the sorted array, the pivot would be at some position. If there are duplicates, the pivot might appear multiple times. The Quickselect returns the pivot at index p, meaning that in the sorted array, the element at index p is the pivot. But there might be other pivots at indices less than p? In the left part, we have elements <= pivot, so if there are duplicates, they are in the left part. So the sorted array would have the left part (which is unsorted) then the pivot, then the right part. But the left part may contain elements equal to the pivot. So in the sorted array, the pivot might appear multiple times, and the one we have at index p is one of them. So the first p elements (0 to p-1) are the smallest p elements? They are all <= the pivot, but they might not be the smallest p because there could be an element in the right part that is less than the pivot? No, the right part is > pivot. So the left part (0 to p-1) are all <= pivot and the right part (p+1 to end) are > pivot. So the smallest p elements are exactly the left part? Not necessarily: because the left part has p elements that are <= pivot, but there might be more than p elements that are <= pivot? Actually, the left part has p elements (indices 0 to p-1) and the pivot at p is also <= pivot. So there are at least p+1 elements that are <= pivot. But the left part has exactly p elements. So the smallest p elements are the left part? Not necessarily: because if the left part contains duplicates of the pivot, then the pivot at p is also one of the smallest p+1? But the left part might contain elements that are equal to the pivot, so the smallest p elements are not necessarily all less than the pivot? They are <= pivot, but the pivot at p is also <= pivot. So the set of the smallest p elements might include some of the left part and possibly the pivot? But the pivot is at index p, so if we take the first p elements (0 to p-1), we are missing the pivot? Actually, the first p elements are indices 0 to p-1, which are p elements. The pivot is at p. So the smallest p elements are the first p elements? Not necessarily: because if there is an element in the left part that is equal to the pivot, then that element and the pivot are both among the smallest p+1? But we want the smallest p elements. Since the left part has p elements and they are all <= pivot, and the pivot is at p, then the smallest p elements are exactly the left part? Let's test:
Example: [2,1,1,3] and we are looking for the 2nd smallest (0-indexed, k=2). The sorted array is [1,1,2,3]. The 2nd smallest is 2.
Suppose we choose pivot = 3 (last element). Partition:
i = -1
j=0: 2<=3 -> i=0, swap arr[0] with arr[0] -> [2,1,1,3]
j=1: 1<=3 -> i=1, swap arr[1] with arr[1] -> [2,1,1,3]
j=2: 1<=3 -> i=2, swap arr[2] with arr[2] -> [2,1,1,3]
then swap arr[i+1]=arr[3] with pivot? Actually, the pivot is at index 3, so after the loop, we swap arr[i+1] with arr[high] (which is the pivot). So we swap arr[3] with arr[3] -> no change. Then return index 3.
So the pivot ends up at index 3. But we are looking for k=2, so we recurse on the left part (0 to 2). Then we might choose pivot=1 (last element of left part). Partition [2,1,1] with pivot=1:
i=-1
j=0: 2<=1? No.
j=1: 1<=1 -> i=0, swap arr[0] and arr[1] -> [1,2,1]
j=2: 1<=1 -> i=1, swap arr[1] and arr[2] -> [1,1,2]
then swap arr[i+1]=arr[2] with pivot (arr[2] is pivot? Actually, pivot is at index 2? In this call, the high index is 2, so the pivot is arr[2]=1. After the loop, we swap arr[i+1] with arr[high]. i=1, so swap arr[2] with arr[2] -> no change. Return index 2.
Now the pivot is at index 2, and we are looking for k=2? But in this subarray, the indices are 0,1,2. We are looking for the 2nd smallest in the entire array, but in this subarray we are looking for the 2nd smallest? Actually, we adjusted k? In the first call, we had k=2 and the array size 4. We partitioned and got pivot at index 3, which is > k, so we recurse on the left part (0 to 2) with the same k=2. Then in the subarray of size 3, we are looking for the 2nd smallest (0-indexed in the subarray? No, we keep the same k? Actually, when we recurse on the left part, the k remains the same because we are looking for the kth smallest in the entire array, and the left part has indices 0 to 2, which are the first 3 elements. So we are still looking for the 2nd smallest in the entire array, which in the left part is the 2nd smallest of the left part? Not exactly: because the left part contains the smallest 3 elements? In this case, the left part [1,1,2] are the smallest 3? Actually, the entire array is [1,1,2,3]. The smallest 3 are [1,1,2]. So the 2nd smallest in the entire array is the 2nd smallest in the left part? The left part sorted is [1,1,2]. The 0th smallest in the left part is 1, the 1st is 1, the 2nd is 2. So the 2nd smallest in the entire array is 2, which is at index 2 in the left part. So when we find the pivot at index 2 in the left part, we return the value 2. So then the array is partitioned such that the left part of the left part (0 to 1) are <=2, and the pivot at 2 is 2. So the first two elements (0 and 1) are <=2, and they are [1,1]. The maximum of the first two is 1, which is the 1st smallest? But we want the 1st smallest for the even case? Actually, for n=4, we want the 1st and 2nd smallest (0-indexed). We have the 2nd smallest (2). Now the first two elements (0 and 1) are the smallest two? They are [1,1], so the 1st smallest is 1. And indeed, the median is (1+2)/2=1.5.
So in this example, after finding the 2nd smallest (k=2), the first two elements (0 and 1) are the smallest two? They are the 0th and 1st smallest? The 0th smallest is 1 and the 1st smallest is 1. So the maximum of the first two is 1, which is the 1st smallest? Actually, the 1st smallest is the second smallest? Wait, the 0th smallest is the smallest, the 1st smallest is the second smallest. So in [1,1], the 0th smallest is 1 and the 1st smallest is 1. So the maximum of the first two is 1, which is the 1st smallest? But we want the 1st smallest (which is the second smallest in 1-indexed). So it works.
But what if the first two were [1,2]? Then the maximum is 2, which would be the 1st smallest? But in the array [1,2,3,4], the 1st smallest is 2? Actually, the 0th smallest is 1, the 1st smallest is 2. So yes, the maximum of the first two (when k=2) is the 1st smallest.
Therefore, for even n, after we find the kth smallest (with k=n//2), we can find the (k-1)th smallest by taking the maximum of the first k elements.
But note: the first k elements are indices 0 to k-1? In the example above, k=2, and we took the first two elements (0 and 1). But after Quickselect, the element at index k (2) is the kth smallest. So the first k elements are indices 0 to k-1? Actually, the first k elements are the ones with indices less than k? In 0-indexed, the first k elements are indices 0 to k-1. So we need to take the maximum of arr[0..k-1].
However, what if there are duplicates? Example: [1,1,1,1]. k=2. The 2nd smallest is 1. The first two elements are [1,1] and the maximum is 1, which is the 1st smallest? The 1st smallest (0-indexed) is the second smallest? In this array, all are 1. So the 0th,1st,2nd,3rd are all 1. So the maximum of the first two is 1, which is the 1st smallest? Yes.
So algorithm for even n:
k = n//2
quickselect(arr, k) # now arr[k] is the kth smallest
m1 = max(arr[0:k]) # the (k-1)th smallest? Actually, the (k-1)th smallest is the largest among the first k? Let's see: the first k elements are the smallest k? They are all <= arr[k]. And the (k-1)th smallest is the largest among the first k? Because the first k elements are the 0th to (k-1)th smallest? Not exactly: the first k elements are the smallest k elements? In the example [1,2,3,4], the first two are [1,2] which are the 0th and 1st smallest. The 1st smallest is the larger of the two? Yes. In [1,1,2,3], the first two are [1,1] and the 1st smallest is 1 (the larger of the two 1's? They are equal). So it seems that the (k-1)th smallest is the maximum of the first k elements.
But wait: what if the array is [1,3,2,4] and we get after Quickselect for k=2: [1,2,3,4]. Then the first two are [1,2] and the maximum is 2, which is the 1st smallest? Yes.
So it seems correct.
However, note that Quickselect modifies the array. So if we want to keep the original array, we might need to copy. But the problem does not specify whether we can modify the input. We'll assume we can modify, or we can work on a copy.
Steps for even n:
k = n//2
quickselect(arr, k) # places the kth smallest at index k
m1 = max(arr[0:k]) # the (k-1)th smallest
m2 = arr[k] # the kth smallest
median = (m1 + m2) / 2.0
But wait: what if the array has an odd number of elements? Then we just do quickselect for k = n//2 (0-indexed) and return arr[k].
However, note: for odd n, the median is the element at index n//2 (0-indexed). So we can do:
if n % 2 == 1:
k = n//2
quickselect(arr, k)
return arr[k]
else:
k = n//2
quickselect(arr, k)
m1 = max(arr[0:k])
m2 = arr[k]
return (m1 + m2) / 2.0
But note: for even n, the median is the average of the (n/2-1)th and (n/2)th smallest (0-indexed). And we are taking the maximum of the first k (which is the (k-1)th smallest) and the kth smallest. That should be correct.
However, what if the array has negative numbers? The same logic applies.
But what about the case when there are many duplicates? Example: [5,5,5,5,5,5]. n=6, k=3. We want the 2nd and 3rd smallest (0-indexed). Both are 5. After Quickselect for k=3, we have the array partitioned such that the first 3 elements are <=5 and the pivot at index 3 is 5. The first three are [5,5,5] and the maximum is 5. So m1=5, m2=5, median=5. Correct.
However, there is a catch: when we do quickselect for k, we are modifying the array. Then when we take the max of the first k, we are using the modified array. That's fine because the first k elements are the smallest k? But note: the quickselect for k does not guarantee that the first k elements are the smallest k? It guarantees that the element at index k is the kth smallest, and the elements at indices 0 to k-1 are <= the kth smallest. But are they the smallest k? They are k elements that are <= the kth smallest, but there might be more than k elements that are <= the kth smallest? Actually, the pivot at index k is the kth smallest, so there are exactly k elements that are less than or equal to the kth smallest? Not necessarily because of duplicates. But the left part (0 to k-1) has k elements that are <= the kth smallest. And the pivot at k is also <= the kth smallest (equal). So there are at least k+1 elements that are <= the kth smallest? But the kth smallest is defined as the element that would be at index k in the sorted array. So in the sorted array, the element at index k is the kth smallest, and the elements at indices 0 to k-1 are the 0th to (k-1)th smallest. So the first k elements in the sorted array are the 0th to (k-1)th smallest. Therefore, in our partitioned array, the first k elements (0 to k-1) are the smallest k? Not necessarily sorted, but they are the set of the smallest k? Yes, because if there were an element in the right part (indices > k) that is less than the kth smallest, that would contradict the fact that the kth smallest is at index k. So the first k elements (0 to k-1) are indeed the smallest k elements? But note: the left part (0 to k-1) are <= the kth smallest, and the right part (k+1 to end) are >= the kth smallest. So the smallest k elements must be in the left part and possibly the pivot? But the pivot is at index k, which is not in the left part. So the left part has k elements that are <= the kth smallest, but the kth smallest itself is at index k. So the set of the smallest k elements is exactly the left part? Not necessarily: because if there is an element equal to the kth smallest in the left part, then the left part contains that element and the pivot is also equal. But the smallest k elements are the ones that are less than or equal to the kth smallest, and there are exactly k of them? Actually, the kth smallest is the element that has at least k elements that are less than or equal to it? And the (k-1)th smallest is the element that has at least k-1 elements that are less than or equal to it? This is getting too deep.
Let me think differently: In the sorted array, the first k elements (indices 0 to k-1) are the smallest k elements. After Quickselect for the kth smallest, we have the array partitioned such that the element at index k is the kth smallest. And the elements at indices 0 to k-1 are all <= the kth smallest. But are they exactly the smallest k? Consider an example: [1,2,2,3] and k=2 (0-indexed). The sorted array is [1,2,2,3]. The 2nd smallest is 2. The smallest k=2 elements are [1,2]. After Quickselect, we might have the array as [1,2,2,3] or [2,1,2,3] etc. In [2,1,2,3], the first two are [2,1]. Are they the smallest two? Yes, because the smallest two are 1 and 2. But note that there are two 2's. The first two contain one 2 and one 1, so they are the smallest two? The smallest two are 1 and 2 (one of the 2's). So the set {2,1} is the set of the smallest two? Yes. In [1,2,2,3], the first two are [1,2] and that's the smallest two. So it works.
But what if the array is [2,2,2,2] and k=2? The smallest two are two of the 2's. After Quickselect, we might have [2,2,2,2] or any permutation. The first two are [2,2] and that's the smallest two? Yes.
So it seems that the first k elements (0 to k-1) are indeed the smallest k elements? Not necessarily in sorted order, but as a set, they are the smallest k. And the maximum of these k elements is the kth smallest? Wait, the kth smallest is the largest among the smallest k? Because the smallest k elements are the 0th to (k-1)th smallest? Actually, the kth smallest is the (k)th smallest, which is one more than the (k-1)th. So the maximum of the smallest k is the (k-1)th smallest? Let's see:
Smallest k elements: let S be the set of the k smallest elements.
The (k-1)th smallest is the maximum of S? Because S has k elements and the (k-1)th smallest is the largest in S? Actually, the (k-1)th smallest is the kth smallest in 1-indexed? I'm confused.
Let's list:
Sorted array: [a0, a1, a2, ..., a_{k-1}, a_k, ...]
a0 is the 0th smallest.
a1 is the 1st smallest.
...
a_{k-1} is the (k-1)th smallest.
a_k is the kth smallest.
So the smallest k elements are a0, a1, ..., a_{k-1}. The maximum of these is a_{k-1}, which is the (k-1)th smallest.
Therefore, after Quickselect for the kth smallest, we have the array partitioned such that the first k elements (0 to k-1) are the smallest k? But note: the pivot is at index k, and the first k elements are indices 0 to k-1. So the set of the first k elements is exactly the set of the smallest k elements? Not necessarily: because the pivot at index k is the kth smallest, and the smallest k elements are the 0th to (k-1)th, which are all <= the kth smallest. And the first k elements (0 to k-1) are all <= the kth smallest. But are they exactly the smallest k? What if one of the smallest k elements is at index k? That cannot happen because the element at index k is the kth smallest, and the smallest k are the 0th to (k-1)th, which are strictly less than or equal to the (k-1)th? Actually, the (k-1)th smallest might be equal to the kth smallest. In that case, the smallest k elements include some of the duplicates of the kth smallest. But the element at index k is the kth smallest, and the smallest k elements are the ones that are less than or equal to the (k-1)th smallest? This is messy.
Given the time, I think the safe way for even n is to run two Quickselects: one for the (k-1)th and one for the kth. But we can do:
m1 = quickselect(arr, k-1) # for the (k-1)th smallest
m2 = quickselect(arr, k) # for the kth smallest
But note: after the first Quickselect, the array is partitioned for the (k-1)th smallest. Then for the second Quickselect, we are looking for the kth smallest in the entire array. But the array is now partially partitioned. We can adjust: after the first Quickselect, the element at index k-1 is the (k-1)th smallest. Then the elements at indices 0 to k-2 are <= that, and the elements at indices k to n-1 are >= that. But we want the kth smallest, which is the smallest element in the right part (indices k to n-1)? Not necessarily: because the right part has elements >= the (k-1)th smallest, but there might be duplicates of the (k-1)th smallest in the right part? Actually, in the partition for the (k-1)th smallest, the pivot is at index k-1, and the left part (0 to k-2) are <= pivot, and the right part (k to n-1) are >= pivot. So the kth smallest must be in the right part? Because the left part has k-1 elements (0 to k-2) and the pivot at k-1. So the smallest k elements are the left part (k-1 elements) and the pivot? That would be k elements? But the pivot is the (k-1)th smallest, so the smallest k elements would be the left part plus the pivot? That's k elements? Actually, the left part has k-1 elements, and the pivot is one, so total k. But the kth smallest is the next one after the (k-1)th? So the kth smallest is the smallest element in the right part? Yes, because the right part (k to n-1) are all >= the (k-1)th smallest, and the smallest among them is the kth smallest. Therefore, after the first Quickselect for the (k-1)th smallest, we can do:
m2 = min(arr[k:]) # but that would be O(n-k) which is O(n). So total O(n) + O(n) = O(n). But we are doing two Quickselects? Actually, the first Quickselect is O(n) on average, and then finding the minimum in the right part is O(n-k) which is about n/2, so total 1.5n.
Alternatively, we can run Quickselect for the kth smallest first, then the (k-1)th smallest is the maximum of the first k? But we already argued that might not be correct because the first k elements might not be the smallest k? Wait, after Quickselect for the kth smallest, the element at index k is the kth smallest. The first k elements (0 to k-1) are <= the kth smallest. But are they the smallest k? The smallest k elements are the 0th to (k-1)th smallest. And the kth smallest is at index k. So the smallest k elements are exactly the first k? Not necessarily: because the first k elements are indices 0 to k-1, and they are <= the kth smallest. But the kth smallest is at index k. So the set of the smallest k elements must be a subset of the first k+1 elements? Actually, the smallest k elements are the ones that are less than or equal to the (k-1)th smallest? This is too confusing.
Given the complexity, I think the simplest is:
If n is odd:
k = n//2
return quickselect(arr, k) # quickselect returns the kth smallest
If n is even:
k1 = n//2 - 1
k2 = n//2
m1 = quickselect(arr, k1)
# Now the array is partitioned for k1. The element at index k1 is the k1th smallest.
# The smallest k1+1 elements are in the left part (0 to k1) and the pivot at k1? Actually, after quickselect for k1, the array is partitioned such that:
# arr[0..k1-1] <= arr[k1] and arr[k1+1..n-1] >= arr[k1].
# So the k2th smallest (which is the next one) must be the smallest element in the right part (arr[k1+1..n-1]).
# But note: there might be duplicates of arr[k1] in the right part? In the partition, we used <= for the left, so elements equal to the pivot are in the left part? Actually, in the standard Lomuto, we use <=, so elements equal to the pivot are in the left part? Wait, the pivot is at index k1, and the left part is indices 0 to k1-1? No, in the partition, the pivot is placed at index i+1, and the left part is from low to i. So the left part does not include the pivot. So the left part (0 to k1-1) are <= pivot, and the pivot is at k1. So the right part (k1+1 to end) are > pivot. Therefore, there are no duplicates of the pivot in the right part. So the k2th smallest is the smallest element in the right part? Because the right part has elements > pivot, and the smallest among them is the next smallest after the pivot? But what if there are elements equal to the pivot in the left part? Then the k2th smallest might be equal to the pivot? Actually, the k2th smallest is the (k1+1)th smallest. The k1th smallest is the pivot. The next smallest could be another pivot? But in the right part, we have elements > pivot, so the next smallest is the minimum of the right part? But what if the left part contains duplicates of the pivot? Then the pivot at k1 is one of them, and the left part might contain more. But the left part has k1 elements (0 to k1-1) that are <= pivot. And the pivot at k1 is the k1th smallest. So the smallest k1+1 elements are the left part (k1 elements) and the pivot? That would be k1+1 elements. But the (k1+1)th smallest would be the next one after the pivot. Since the right part has elements > pivot, the (k1+1)th smallest is the smallest in the right part.
So after the first Quickselect for k1, we have:
m1 = arr[k1]
Now we need m2 = the smallest element in arr[k1+1:].
We can find that by a linear scan: O(n-k1) which is about n/2.
Then median = (m1 + m2) / 2.
But wait: what if the array has duplicates and the pivot appears in the left part? Then the left part has elements <= pivot, and the pivot is at k1. The smallest k1+1 elements are the left part (k1 elements) and the pivot? But the left part might contain elements equal to the pivot, so the set of the smallest k1+1 elements includes the left part and the pivot? Actually, the left part has k1 elements that are <= pivot. The pivot is at k1. So the set of the first k1+1 elements (0 to k1) are all <= pivot? And the pivot is at k1. So the smallest k1+1 elements are exactly the first k1+1 elements? Not necessarily: because the left part might contain duplicates of the pivot, but then the pivot at k1 is also a duplicate. So the first k1+1 elements are the smallest k1+1? But note: the right part has elements > pivot, so they are not among the smallest k1+1. Therefore, the smallest k1+1 elements are exactly the first k1+1 elements (0 to k1). And the (k1+1)th smallest is the largest among the first k1+1? Actually, the (k1+1)th smallest is the (k1)th smallest in 0-indexed? Wait, we have:
k1 = n//2 - 1 (0-indexed). For n=4, k1=1.
We want the 1st and 2nd smallest (0-indexed). The 1st smallest is the maximum of the first 2? No, the 1st smallest is the second smallest? Actually, the 0th smallest is the smallest, the 1st is the second smallest.
After quickselect for k1=1, the array is partitioned such that the first 1 element (0) is <= the pivot at index 1? Actually, the left part is indices 0 to k1-1? k1-1=0, so the left part has one element? Wait, after quickselect for k1, the pivot is at index k1. The left part is from 0 to k1-1. So for k1=1, the left part is index 0 only. And the pivot is at index 1. So the first k1+1 = 2 elements are indices 0 and 1. The smallest 2 elements are indices 0 and 1? And the 1st smallest (0-indexed) is the larger of the two? Actually, the 0th smallest is the smaller of the two, and the 1st smallest is the larger. So the 1st smallest is the maximum of the first two? But we have only two elements: the left part (one element) and the pivot. So the maximum of the first two is the 1st smallest? Yes.
But we want the 1st and 2nd smallest? Actually, for n=4, we want the 1st and 2nd smallest (0-indexed). We have the 1st smallest as the maximum of the first two? And the 2nd smallest is the minimum of the right part? But the right part starts at index 2. So we have:
m1 = maximum of arr[0:2] # which is the 1st smallest?
m2 = minimum of arr[2:4] # which is the 2nd smallest?
Then median = (m1+m2)/2.
But wait, in the example [1,2,3,4]:
After quickselect for k1=1 (the 1st smallest), we might have [1,2,3,4] or [2,1,3,4].
If [1,2,3,4]:
first two: [1,2] -> max=2 (which is the 1st smallest? The 1st smallest in 0-indexed is the second smallest, which is 2. Correct.)
right part: [3,4] -> min=3 (which is the 2nd smallest? The 2nd smallest in 0-indexed is the third smallest? Wait, for n=4, the 0th smallest is 1, the 1st is 2, the 2nd is 3, the 3rd is 4. So we want the 1st and 2nd: which are 2 and 3. So m1=2, m2=3 -> median=2.5. Correct.
If [2,1,3,4]:
first two: [2,1] -> max=2 (1st smallest)
right part: [3,4] -> min=3 (2nd smallest). Same.
Example [1,1,2,3]:
Sorted: [1,1,2,3]. We want the 1st and 2nd smallest (0-indexed): 1 and 2.
After quickselect for k1=1 (the 1st smallest), we want the element at index 1 to be the 1st smallest. The 1st smallest is 1. We might get [1,1,2,3] or [1,1,2,3] etc. Suppose we get [1,1,2,3]:
first two: [1,1] -> max=1 (1st smallest)
right part: [2,3] -> min=2 (2nd smallest). Correct.
Example [1,2,2,3]:
Sorted: [1,2,2,3]. We want the 1st and 2nd: 2 and 2.
After quickselect for k1=1 (the 1st smallest is 2). We might get [1,2,2,3] or [2,1,2,3] etc.
If [1,2,2,3]:
first two: [1,2] -> max=2 (1st smallest)
right part: [2,3] -> min=2 (2nd smallest). Correct.
Example [2,2,2,2]:
Sorted: [2,2,2,2]. We want the 1st and 2nd: both 2.
After quickselect for k1=1, we have the pivot at index 1 being 2. The array might be [2,2,2,2].
first two: [2,2] -> max=2
right part: [2,2] -> min=2. Correct.
So this approach seems to work.
Steps for even n:
k1 = n//2 - 1
k2 = n//2
m1 = quickselect(arr, k1) # this places the k1-th smallest at index k1, and partitions the array.
# Now the smallest k1+1 elements are in arr[0..k1] (but not necessarily sorted). The k2-th smallest is the smallest in the right part (arr[k1+1..n-1]).
m2 = min(arr[k1+1:])
return (m1 + m2) / 2.0
But note: after the first quickselect, the array is partitioned such that arr[k1] is the k1-th smallest, and the left part (0 to k1-1) are <= arr[k1], and the right part (k1+1 to end) are >= arr[k1]. Since we used <= in the partition, the right part has elements >= arr[k1], but note that there might be duplicates of arr[k1] in the left part? Actually, in the partition, we put elements <= pivot in the left part, so the left part (0 to k1-1) are <= pivot, and the pivot is at k1. The right part is > pivot. So the right part has no duplicates of the pivot. Therefore, the smallest element in the right part is the (k1+1)th smallest? Because the left part has k1 elements that are <= pivot, and the pivot is the k1-th smallest. So the next smallest must be the smallest in the right part, which is > pivot. So m2 is indeed the k2-th smallest.
However, what if the array has duplicates and the pivot appears in the left part? Then the left part has some duplicates of the pivot, but the pivot at k1 is one of them. The smallest k1+1 elements include the left part (k1 elements) and the pivot? That's k1+1 elements. But the left part has k1 elements that are <= pivot, and the pivot is also <= pivot. So the set of the first k1+1 elements (0 to k1) are all <= pivot. And the right part has elements > pivot. So the (k1+1)th smallest is the smallest element in the right part? Yes.
Therefore, the algorithm:
def quickselect(arr, k):
# returns the kth smallest element (0-indexed) and partitions the array around it.
# We can implement Quickselect with random pivot to avoid worst-case.
def find_median(arr):
n = len(arr)
if n == 0:
return None
if n % 2 == 1:
k = n//2
return quickselect(arr, k)
else:
k1 = n//2 - 1
k2 = n//2
m1 = quickselect(arr, k1)
# Now arr[k1] is the k1-th smallest.
# The k2-th smallest is the minimum of arr[k1+1:]
m2 = min(arr[k1+1:])
return (m1 + m2) / 2.0
But note: the quickselect for k1 modifies the array. Then we take the min of the right part. This is O(n) for the min, but the quickselect is O(n) on average. So total O(n) on average.
However, we must be cautious: the quickselect for k1 might not put the k1-th smallest at index k1? Actually, the quickselect algorithm returns the kth smallest and places it at index k. So after calling quickselect(arr, k1), the element at index k1 is the k1-th smallest. And the array is partitioned such that the left part (0 to k1-1) are <= arr[k1] and the right part (k1+1 to end) are >= arr[k1]. So the right part has elements >= arr[k1]. Therefore, the minimum of the right part is the smallest element that is >= arr[k1]. And since the k1-th smallest is arr[k1], the next smallest (k2-th) must be the smallest in the right part? Yes, because the left part and the pivot are the smallest k1+1 elements? Actually, the left part has k1 elements that are <= arr[k1], and the pivot is arr[k1]. So the set of the smallest k1+1 elements is the union of the left part and the pivot. Therefore, the (k1+1)th smallest is the smallest element that is greater than arr[k1]? But what if there are duplicates of arr[k1] in the left part? Then the left part contains some duplicates, and the pivot is one. So the smallest k1+1 elements include the left part (which may contain duplicates) and the pivot. But the pivot is at index k1. The left part has k1 elements that are <= pivot. So the total number of elements that are <= pivot is at least k1+1 (the left part plus the pivot). But the k1-th smallest is the pivot, so the (k1+1)th smallest is the next element that is greater than the pivot? Because if there are duplicates, then the (k1+1)th smallest might be equal to the pivot? But the pivot is the k1-th smallest, and if there are duplicates, then the (k1+1)th smallest could also be equal to the pivot? However, in the partition, we put all elements <= pivot on the left? Actually, in the standard Lomuto, we put elements <= pivot on the left, but the pivot itself is placed at the end of the left part? Wait, in the partition, we have:
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
swap arr[i] and arr[j]
swap arr[i+1] and arr[high]
return i+1
So after partition, the pivot is at index i+1. The elements at indices low to i are <= pivot, and the elements at indices i+2 to high are > pivot. So the pivot is at index i+1, and the left part does not include the pivot. Therefore, the left part (low to i) has elements <= pivot, and the pivot is separate. So the number of elements that are <= pivot is (i - low + 1) + 1? Actually, the left part has (i - low + 1) elements, and the pivot is one more. So total (i - low + 2) elements that are <= pivot? But wait, the left part has elements <= pivot, and the pivot is also <= pivot. So the total count of elements <= pivot is (i - low + 1) + 1 = i - low + 2.
But in our quickselect, we are looking for the k1-th smallest. When the pivot ends up at index p, then the number of elements that are <= pivot is (p - low) + 1? Because the left part has (p - low) elements? Actually, the left part is from low to p-1, which is (p-1 - low + 1) = p - low. Then plus the pivot at p. So total p - low + 1.
Therefore, if the pivot is at index k1, then the number of elements that are <= pivot is k1 - 0 + 1 = k1+1. So there are exactly k1+1 elements that are <= the pivot. And the pivot is the k1-th smallest? That would mean that there are k1 elements that are less than or equal to the pivot, but the pivot itself is the (k1+1)th? This is contradictory.
Let's use an example: [1,2,3] and we are looking for the 1st smallest (0-indexed, k=1). The pivot might be 2. Partition:
low=0, high=2, pivot=2.
i=-1
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> [1,2,3]
j=1: 2<=2 -> i=1, swap arr[1] with arr[1] -> [1,2,3]
then swap arr[i+1]=arr[2] with pivot? But pivot is at index 2, so we swap arr[2] with arr[2] -> no change. Return index 2.
So pivot ends up at index 2. But we were looking for k=1. Since pivot index 2 > k=1, we recurse on left part (0 to 1). Then in the left part, we look for the 1st smallest. In the subarray [1,2], we might choose pivot=2. Partition:
low=0, high=1, pivot=2.
i=-1
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> [1,2]
then swap arr[i+1]=arr[1] with pivot (arr[1] is pivot) -> no change. Return index 1.
Now pivot is at index 1, which equals k=1 (in the subarray, but in the original array index? Actually, in the original array, the subarray is indices 0 and 1. So pivot at index 1 of the original array. So we return arr[1]=2. So the 1st smallest is 2.
Now, after this quickselect, the array might be [1,2,3] or [2,1,3] etc. In the first case, the pivot is at index 1. The left part is index 0: [1]. The right part is index 2: [3]. So the first k1+1 = 2 elements are indices 0 and 1: [1,2]. The (k1+1)th smallest (which is the 2nd smallest in 0-indexed? Actually, k1=1, so k2=2) is the smallest in the right part? The right part is [3], so min is 3. But the 2nd smallest in [1,2,3] is 2? Wait, the 0th smallest is 1, the 1st is 2, the 2nd is 3. So we want the 1st and 2nd: 2 and 3. But m1=2 (from quickselect) and m2=min(arr[2:])=3. That gives (2+3)/2=2.5, but the median of [1,2,3] is 2? Actually, for n=3 (odd) we would have returned the 1st smallest? But here n=3 is odd, so we wouldn't use this even case. This example is for odd n.
I'm getting lost. Given the time, I think it's better to implement a quickselect that returns the kth smallest without modifying the original array? But the problem doesn't specify.
Alternatively, we can do:
For even n:
We want the (n/2-1)th and (n/2)th smallest.
We can run quickselect twice: first for k = n//2, then for k = n//2 - 1, but on the same array? But after the first quickselect, the array is partitioned. We can run the second quickselect on the left part? Because after the first quickselect for the k2 = n//2, the element at index k2 is the k2-th smallest. Then the (k2-1)th smallest must be in the left part (0 to k2-1) and it is the maximum of that left part? As argued earlier.
So:
k = n//2
quickselect(arr, k) # now arr[k] is the k-th smallest.
m2 = arr[k]
m1 = max(arr[0:k]) # the (k-1)th smallest.
return (m1+m2)/2
But we must ensure that the left part (0 to k-1) are the smallest k elements? Actually, after quickselect for k, the array is partitioned such that the first k elements (0 to k-1) are <= arr[k]. And the element at index k is the k-th smallest. So the smallest k elements are exactly the first k? Not necessarily: because there might be duplicates of arr[k] in the left part? But the left part has k elements that are <= arr[k]. And the element at index k is arr[k]. So the set of the smallest k elements is the first k? Wait, the smallest k elements are the 0th to (k-1)th smallest. And the k-th smallest is at index k. So the first k elements are indices 0 to k-1, which are the 0th to (k-1)th? But the element at index k is the k-th smallest, which is not included in the first k. So the first k elements are the smallest k? They are all <= the k-th smallest, but they might not be exactly the smallest k because the k-th smallest might appear in the left part? Actually, the left part has elements <= the pivot, and the pivot is at index k. So if there is an element in the left part that is equal to the pivot, then that element is one of the smallest k? But the pivot is the k-th smallest, so that element in the left part is also the k-th smallest? That would mean there are at least two occurrences of the k-th smallest. Then the smallest k elements would include that duplicate? But the smallest k elements are the ones that are less than or equal to the (k-1)th smallest? This is too confusing.
Given the complexity, I think the safest is to not rely on the partitioned array for the second median and instead run two quickselects on two copies? But that would be O(n) extra space.
Alternatively, we can write a quickselect that returns the kth smallest without modifying the array? But quickselect typically modifies the array. We can copy the array for each quickselect? That would be O(n) space and O(n) time for each quickselect, so total O(n) time and O(n) space.
Since the problem doesn't specify space constraints, we can do:
if n % 2 == 1:
return quickselect(arr.copy(), n//2)
else:
k1 = n//2 - 1
k2 = n//2
copy1 = arr.copy()
copy2 = arr.copy()
m1 = quickselect(copy1, k1)
m2 = quickselect(copy2, k2)
return (m1 + m2) / 2.0
But that makes two copies and two quickselects, so O(n) space and O(n) time on average.
However, we can do it with one copy if we do:
copy = arr.copy()
if n % 2 == 1:
return quickselect(copy, n//2)
else:
k1 = n//2 - 1
k2 = n//2
m1 = quickselect(copy, k1)
# Now copy is partitioned for k1. We need the k2-th smallest in the original array? But note: after the first quickselect, the array is partitioned, and the k2-th smallest is the minimum of the right part? As argued earlier.
m2 = min(copy[k1+1:])
return (m1 + m2) / 2.0
This uses one copy and one quickselect and one min over half the array. So O(n) time and O(n) space.
But note: the min over the right part is O(n) in the worst case, but on average the right part has size about n/2, so it's O(n). And the quickselect is O(n) on average. So total O(n) on average.
Let's test with an example:
arr = [3,1,4,2]
n=4, k1=1, k2=2.
copy = [3,1,4,2]
quickselect(copy, 1):
We want the 1st smallest (0-indexed) which is the second smallest? Actually, 0-indexed: 0th smallest is 1, 1st is 2, 2nd is 3, 3rd is 4. So we want 2.
Let's run quickselect for k=1.
Suppose we choose pivot=2 (last element). Partition:
i=-1
j=0: 3<=2? No.
j=1: 1<=2 -> i=0, swap copy[0] and copy[1] -> [1,3,4,2]
j=2: 4<=2? No.
then swap copy[i+1]=copy[1] with pivot (copy[3]=2) -> [1,2,4,3]
return index 1.
So m1 = copy[1] = 2.
Now copy = [1,2,4,3]
The right part is copy[2:] = [4,3]. min = 3.
So median = (2+3)/2 = 2.5. Correct.
Another example: [1,2,3,4]
quickselect for k=1:
pivot might be 4 -> partition: [1,2,3,4] -> pivot at index 3 -> recurse on left part [1,2,3] for k=1.
In [1,2,3]: pivot=3 -> partition: [1,2,3] -> pivot at index 2 -> recurse on left part [1,2] for k=1.
In [1,2]: pivot=2 -> partition: [1,2] -> pivot at index 1 -> return 2.
So m1=2.
copy after first quickselect: might be [1,2,3,4] or [1,2,4,3] etc. But note: the array is partitioned for k=1, so the element at index 1 is 2, and the left part (index0) is <=2, and the right part (indices2,3) are >=2. So copy[0] is 1, copy[1]=2, copy[2:]=[3,4] or [4,3]. min of right part is 3. So median=2.5.
Example with duplicates: [1,1,2,2]
n=4, k1=1.
quickselect for k=1: we want the 1st smallest (0-indexed). The sorted array is [1,1,2,2]. The 1st smallest is 1? Actually, 0th smallest is 1, 1st smallest is 1, 2nd is 2, 3rd is 2. So we want m1=1 and m2=2? Wait, for even n, we want the 1st and 2nd smallest? Actually, for n=4, the median is the average of the 1st and 2nd smallest (0-indexed)? That would be (1+2)/2=1.5. But the sorted array is [1,1,2,2], so the median is (1+2)/2=1.5.
Let's run quickselect for k=1:
copy = [1,1,2,2]
pivot might be 2 (last element). Partition:
i=-1
j=0: 1<=2 -> i=0, swap copy[0] with copy[0] -> [1,1,2,2]
j=1: 1<=2 -> i=1, swap copy[1] with copy[1] -> [1,1,2,2]
j=2: 2<=2 -> i=2, swap copy[2] with copy[2] -> [1,1,2,2]
then swap copy[i+1]=copy[3] with pivot (copy[3] is pivot) -> no change. Return index 3.
Since pivot index 3 > k=1, we recurse on left part [1,1,2] for k=1.
In [1,1,2]: pivot=2 -> partition:
i=-1
j=0: 1<=2 -> i=0, swap -> [1,1,2]
j=1: 1<=2 -> i=1, swap -> [1,1,2]
then swap copy[i+1]=copy[2] with pivot -> no change. Return index 2.
Since 2 > k=1, recurse on left part [1,1] for k=1.
In [1,1]: pivot=1 -> partition:
i=-1
j=0: 1<=1 -> i=0, swap -> [1,1]
then swap copy[i+1]=copy[1] with pivot -> no change. Return index 1.
Now pivot index 1 == k=1 (in the subarray of size 2, but in the original array? We are using indices within the subarray? Actually, we are passing the array and low/high. So in the subarray [1,1] (which are indices 0 and 1 of the original array? Actually, in the first call, the array is [1,1,2,2]. We then recurse on left part [1,1,2] which are indices 0,1,2. Then we recurse on left part of that, which is [1,1] at indices 0 and 1. So when we return index 1 in that subarray, it corresponds to index 1 in the original array. So m1 = copy[1] = 1.
Now copy is partitioned for k=1. The element at index 1 is 1. The left part (index0) is [1] and the right part (indices2,3) are [2,2]. So m2 = min(copy[2:]) = 2. Then median = (1+2)/2 = 1.5. Correct.
So this seems to work.
However, note that the quickselect we implemented above uses Lomuto partition and returns the index of the pivot. But in the recursive calls, we adjust the array bounds. We must be careful to implement quickselect correctly.
Let me write the quickselect function:
def quickselect(arr, k, low=0, high=None):
if high is None:
high = len(arr)-1
if low == high:
return arr[low]
pivot_index = random.randint(low, high)
pivot_index = partition(arr, low, high, pivot_index)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, k, low, pivot_index-1)
else:
return quickselect(arr, k, pivot_index+1, high)
But note: the partition function should use the pivot_index and return the final index of the pivot.
Alternatively, we can use the Lomuto partition with the pivot at the end:
def partition(arr, low, high, pivot_index):
pivot = arr[pivot_index]
# move pivot to end
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# move pivot to its final place
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
But note: in the even case, after quickselect for k1, we take min(arr[k1+1:]). But what if k1+1 is out of bounds? If k1 = n//2 -1, then for n=2, k1=0, k1+1=1, which is valid. For n=0, we already handled.
So the final function:
import random
def partition(arr, low, high, pivot_index):
pivot = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
def quickselect(arr, k, low=0, high=None):
if high is None:
high = len(arr) - 1
if low == high:
return arr[low]
pivot_index = random.randint(low, high)
pivot_index = partition(arr, low, high, pivot_index)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, k, low, pivot_index-1)
else:
return quickselect(arr, k, pivot_index+1, high)
def find_median(nums):
if not nums:
return None
n = len(nums)
arr = nums.copy() # to avoid modifying the original
if n % 2 == 1:
k = n // 2
return quickselect(arr, k)
else:
k1 = n // 2 - 1
k2 = n // 2
m1 = quickselect(arr, k1)
# Now arr[k1] is the k1-th smallest.
# The k2-th smallest is the minimum of arr[k1+1:]
m2 = min(arr[k1+1:])
return (m1 + m2) / 2.0
However, note: after quickselect for k1, the array is partitioned such that arr[k1] is the k1-th smallest, and the elements from k1+1 to the end are >= arr[k1]. So the minimum of arr[k1+1:] is the smallest element that is >= arr[k1]. But is that the k2-th smallest? Since the left part (0 to k1-1) are <= arr[k1], and the pivot at k1 is arr[k1], the smallest k1+1 elements are the first k1+1 elements (0 to k1). The next smallest (the k2-th) is the smallest element in the right part, which is > arr[k1] (because the right part has elements > arr[k1] due to the partition using <=). But what if there are duplicates of arr[k1] in the left part? Then the left part has some duplicates, and the pivot is one. So the set of the smallest k1+1 elements includes the left part and the pivot. The next smallest must be greater than arr[k1] because the right part has only elements > arr[k1]. So yes, m2 is the k2-th smallest.
But wait: what if the array is [1,2,2,3] and k1=1? The k1-th smallest is 2. After quickselect, the array might be [1,2,2,3]. Then arr[k1]=2, and arr[k1+1:]=[2,3]. The minimum is 2. But the k2-th smallest is also 2? The sorted array is [1,2,2,3]. The k1=1 (1st smallest) is 2? Actually, the 0th smallest is 1, the 1st is 2, the 2nd is 2. So the 1st and 2nd are both 2. So m1=2, m2=2, median=2. Correct.
But in the partition, the right part is supposed to have elements > pivot? In the Lomuto partition, we use <= for the left, so the right part has elements > pivot. In the example [1,2,2,3] with pivot=2 (at the end), we have:
i=-1
j=0: 1<=2 -> i=0, swap -> [1,2,2,3]
j=1: 2<=2 -> i=1, swap -> [1,2,2,3]
j=2: 2<=2 -> i=2, swap -> [1,2,2,3]
then swap arr[i+1]=arr[3] with pivot (arr[3] is 3) -> [1,2,2,3] becomes [1,2,2,3]? Actually, we swap arr[3] with arr[3]? No, we swapped pivot to the end at the beginning? Wait, we moved the pivot to the end at the start: we swapped arr[pivot_index] with arr[high]. So if pivot_index was 3 (value 3), then we swap arr[3] with arr[3]? That does nothing. Then after the loop, we swap arr[i+1] with arr[high]. i=2, so we swap arr[3] with arr[3] again. So the array remains [1,2,2,3]. But the pivot was 3? We were looking for k1=1, and the pivot ended at index 3, which is >1, so we recurse on left part [1,2,2]. Then in that subarray, we might choose pivot=2 (last element). Partition [1,2,2]:
i=-1
j=0: 1<=2 -> i=0, swap -> [1,2,2]
j=1: 2<=2 -> i=1, swap -> [1,2,2]
then swap arr[i+1]=arr[2] with pivot (arr[2] is 2) -> no change. Return index 2.
Now pivot index 2 > k1=1? Actually, in the subarray, the indices are 0,1,2. We are looking for k=1. Since pivot index 2 > 1, we recurse on left part [1,2] for k=1.
In [1,2]: pivot=2 -> partition:
i=-1
j=0: 1<=2 -> i=0, swap -> [1,2]
then swap arr[i+1]=arr[1] with pivot -> no change. Return index 1.
Now pivot index 1 == k=1, so we return arr[1]=2.
Now the array is partitioned for k=1? The element at index 1 is 2. The left part (index0) is [1] and the right part (indices2,3) are [2,3]. But note: in the original array, after the first quickselect, the array might be [1,2,2,3] or something else? Actually, the array was modified during the recursive calls. In the end, the array might be [1,2,2,3] or [1,2,2,3]? Let's see: in the last partition of [1,2], we did nothing. So the array at that point is [1,2] for the subarray. But the original array: we had [1,2,2,3]. When we partitioned the subarray [1,2,2] (indices 0,1,2), we might have swapped? In the partition of [1,2,2], we did:
i=-1
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> no change.
j=1: 2<=2 -> i=1, swap arr[1] with arr[1] -> no change.
then swap arr[2] with arr[2] -> no change.
So the array remains [1,2,2]. Then we recursed on [1,2] (indices 0,1). So the array is still [1,2,2,3]? Actually, the array is the same. So after the quickselect for k1=1, the array is [1,2,2,3] and the element at index 1 is 2. The left part (index0) is [1] and the right part (indices2,3) are [2,3]. So m2 = min([2,3]) = 2. That gives (2+2)/2=2. But the median should be (2+2)/2=2? Actually, for [1,2,2,3], the median is (2+2)/2=2. So it works.
But wait, in this case the right part has an element equal to the pivot? But in the partition, we used <= for the left, so the right part should have elements > pivot. Here the pivot is 2, and the right part has 2 and 3. But 2 is not > 2. So why is 2 in the right part? Because in the partition of the subarray [1,2,2], we used pivot=2 (the last element). In the partition, we put elements <= pivot on the left. So when j=1, arr[1]=2 <=2, so we put it in the left part? Actually, in the loop, j goes from low to high-1. In the subarray [1,2,2] with low=0, high=2, we have j=0 and j=1. For j=1, arr[1]=2 <= pivot (2), so we do i++ and swap. But i starts at -1. After j=0, i=0. Then j=1: i becomes 1, and we swap arr[1] with arr[1] (no change). Then after the loop, we swap arr[i+1] (index 2) with arr[high] (index 2). So the pivot (which was at index 2) is swapped with itself. So the pivot ends up at index 2. And the left part is indices 0 to 1: [1,2]. So the right part is empty? Actually, the right part is from index 2+1 to high? But high is 2, so right part is empty. So in this partition, the pivot is at index 2, and the left part has indices 0 and 1. So the right part is empty. Then when we take min(arr[k1+1:]), k1=1, so we take min(arr[2:]) which is arr[2]=2. So that works.
But in the example [1,2,2,3], after quickselect for k1=1, we have the array as [1,2,2,3] and the pivot at index 1? Actually, we found the k1=1 in the subarray [1,2] and returned 2. But what about the element at index 2? It is also 2. So the right part (index2 and 3) are [2,3]. But according to the partition, if the pivot is at index 1, then the left part is index0 and the right part is indices2 and 3. But in the partition that placed the pivot at index 1, we must have had a partition that put all elements <= pivot in the left part (index0) and the pivot at index1, and the right part has elements > pivot. But here the right part has a 2, which is equal to the pivot. So that partition did not happen? Actually, in the quickselect, we are not necessarily partitioning the entire array for the final pivot. We are recursively partitioning. The final pivot index 1 was achieved in the subarray [1,2] (which are indices 0 and 1 of the original array). In that partition, the pivot was 2 and the array [1,2] was partitioned such that the left part is [1] and the pivot at index1. So the right part in that subarray is empty. But the elements at indices 2 and 3 were not touched in that partition. So they remain as they were. So after the quickselect for k1=1, the array is not necessarily partitioned for the entire array with respect to the pivot at index1? Actually, the quickselect algorithm partitions the array around the pivot and then recurses on one side. So the entire array is partitioned with respect to the pivot that is placed at its final position. But in this case, the pivot that ended up at index1 was from the subarray [1,2]. But what about the elements at indices 2 and 3? They were in the right part of a previous partition? Let's trace:
Initial array: [1,2,2,3]
First call: quickselect(arr, 1, 0, 3)
pivot_index = random, say 3 (value 3). Partition with pivot=3:
i=-1
j=0: 1<=3 -> i=0, swap -> [1,2,2,3]
j=1: 2<=3 -> i=1, swap -> [1,2,2,3]
j=2: 2<=3 -> i=2, swap -> [1,2,2,3]
then swap arr[i+1]=arr[3] with pivot (arr[3] is 3) -> no change. Return index 3.
Since k=1 < 3, recurse on left part (0 to 2).
Second call: quickselect(arr, 1, 0, 2)
pivot_index = random, say 2 (value 2). Partition:
move pivot to end: swap arr[2] with arr[2] -> no change.
i=-1
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> [1,2,2]
j=1: 2<=2 -> i=1, swap arr[1] with arr[1] -> [1,2,2]
then swap arr[i+1]=arr[2] with arr[2] -> no change. Return index 2.
Since k=1 < 2, recurse on left part (0 to 1).
Third call: quickselect(arr, 1, 0, 1)
pivot_index = random, say 1 (value 2). Partition:
move pivot to end: swap arr[1] with arr[1] -> no change.
i=-1
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> [1,2]
then swap arr[i+1]=arr[1] with arr[1] -> no change. Return index 1.
Now k=1 == pivot_index=1, return arr[1]=2.
So after the entire quickselect, the array is [1,2,2,3]? But note: in the second call, we partitioned the subarray [1,2,2] and the pivot ended at index2 of the entire array? Actually, in the second call, the array indices are 0,1,2. The pivot was at index2 of the entire array? Yes, because we passed low=0, high=2. So after the partition, the pivot is at index2 of the entire array. But then we recursed on the left part (0 to 1). So the array after the second call is partitioned such that the element at index2 is the pivot for that call, but we are not done because we are looking for k=1 and the pivot index2 >1. So we recursed on the left part. Then in the third call, we partitioned the subarray [1,2] (indices 0 and 1 of the entire array) and placed the pivot at index1. So the final array is:
index0: 1
index1: 2 (from the third call)
index2: 2 (from the second call, unchanged)
index3: 3 (unchanged)
So the array is [1,2,2,3]. And the element at index1 is 2, which is the k1-th smallest. The left part (0) is [1] and the right part (2,3) are [2,3]. So when we take min of arr[2:], we get 2. So that works.
But what if the pivot in the second call had been placed at index1? That would happen if we had chosen pivot_index=1 in the second call. Let's see:
Second call: quickselect(arr, 1, 0, 2) with pivot_index=1 (value 2).
Partition:
move pivot to end: swap arr[1] with arr[2] -> array becomes [1,2,2]? Wait, arr[1] is 2 and arr[2] is 2, so swapping gives [1,2,2] (same).
i=-1
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> [1,2,2]
j=1: now j goes from low=0 to high-1=1. So j=1: arr[1]=2 <=2 -> i=1, swap arr[1] with arr[1] -> [1,2,2]
then swap arr[i+1]=arr[2] with arr[2] -> no change. Return index 2.
So pivot ends at index2. Then since k=1 <2, we recurse on left part (0 to 1). So same as before.
So it seems that in the second call, the pivot always ends at index2? Because the subarray has 3 elements and we are looking for the 1st smallest. The pivot will be placed at its correct position in the entire array? Not necessarily: because we are only partitioning the subarray. So the pivot index returned is relative to the subarray? Actually, in the partition function, we are given low and high, and we return the index within that range. So in the second call, the pivot index returned is 2, which is the index in the entire array? Because we passed low=0, high=2, and the partition function uses indices from low to high. So the returned index is the absolute index. So after the second call, the pivot is at index2 of the entire array. Then we recurse on low=0, high=1. So the element at index2 is fixed as the pivot for that call, but we are not done because k=1 is less than 2? Actually, k=1 is the index we are looking for in the entire array? In the second call, we are still looking for the 1st smallest in the entire array, but we are only considering the subarray from 0 to 2. Since the pivot is at index2, which is greater than k=1, we know that the kth smallest is in the left part (0 to 1). So we recurse on that.
Therefore, after the quickselect for k1, the element at index k1 is the k1-th smallest, and the array is partitioned such that the elements at indices 0 to k1-1 are <= arr[k1] and the elements at indices k1+1 to n-1 are >= arr[k1]? Not exactly: because the partitioning was done in the context of subarrays. But since we always recurse on the side that contains k, the final pivot index is k1, and at that point, the array is partitioned such that all elements at indices < k1 are <= arr[k1] and all elements at indices > k1 are >= arr[k1]. This is a property of quickselect: when we return, the array is partitioned around the pivot at index k. So yes, after quickselect(arr, k1), we have:
for i in range(k1): arr[i] <= arr[k1]
for i in range(k1+1, n): arr[i] >= arr[k1]
Therefore, the right part (k1+1 to n-1) has elements >= arr[k1]. And since we want the k2-th smallest (which is the next one after the k1-th), and the left part and the pivot are the smallest k1+1 elements, the k2-th smallest is the smallest element in the right part.
So the algorithm is correct.
Time complexity:
Sorting: O(n log n)
Quickselect: average O(n), worst-case O(n^2) but with random pivot the worst-case is unlikely. We can use median-of-medians for O(n) worst-case but that is more complex.
So we can do better on average.
Let's write the code accordingly.
However, note: for even n, we are doing one quickselect and then a min over half the array. The min is O(n) but on average the right part has size about n/2, so it's O(n). So total average time is O(n).
But what about the worst-case? The quickselect can be O(n^2) and the min is O(n), so worst-case O(n^2). But with random pivot, the expected time is O(n).
We can also use the median-of-medians to make quickselect O(n) worst-case, but that is more complex and has larger constant factor.
Given the problem, we'll implement the average O(n) version.
Let's code accordingly.
But note: the problem says "can you do better?" and hints at Quickselect. So we should mention that we can achieve average O(n) with Quickselect.
Now, write the function.
However, the problem says "Write a function to find the median of the list." So we need to write a function.
Let me write the code with detailed comments.
We'll assume the input list can be modified? But we are copying it anyway.
Code:
import random
def partition(arr, low, high, pivot_index):
# Move pivot to the end
pivot = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# Move pivot to its final place
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
def quickselect(arr, k, low=0, high=None):
if high is None:
high = len(arr) - 1
if low == high:
return arr[low]
pivot_index = random.randint(low, high)
pivot_index = partition(arr, low, high, pivot_index)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, k, low, pivot_index-1)
else:
return quickselect(arr, k, pivot_index+1, high)
def median(nums):
if not nums:
return None
n = len(nums)
arr = nums.copy() # work on a copy to avoid modifying the input
if n % 2 == 1:
k = n // 2
return quickselect(arr, k)
else:
k1 = n // 2 - 1
k2 = n // 2
m1 = quickselect(arr, k1)
# After quickselect for k1, arr[k1] is the k1-th smallest.
# The k2-th smallest is the smallest element in the right part.
m2 = min(arr[k1+1:])
return (m1 + m2) / 2.0
Let's test with a few examples.
However, note: what if the array has an even number of elements and after quickselect for k1, the right part is empty? That would happen if k1+1 >= n? But k1 = n//2 -1, so k1+1 = n//2, which is less than n for n>=2. For n=2, k1=0, k1+1=1, which is valid. So the right part is at least one element? Actually, for n=2, after quickselect for k1=0, the array is partitioned such that arr[0] is the smallest. Then arr[1:] is the right part with one element. So it's fine.
But what if after quickselect for k1, the right part has duplicates of arr[k1]? That is possible if the partition did not put all duplicates of the pivot in the left part? In the Lomuto partition, we use <=, so duplicates of the pivot are placed in the left part? Actually, in the partition, we move elements <= pivot to the left. So if there is an element equal to the pivot, it will be moved to the left part? But the pivot itself is moved to the end at the beginning, and then during the loop, we compare with the pivot value. So if there is an element equal to the pivot, it will be moved to the left part? Let's see:
Example: [2,1,2] with pivot=2 (at index2).
Move pivot to end: swap index2 with index2 -> no change.
i=-1
j=0: 2<=2 -> i=0, swap arr[0] with arr[0] -> [2,1,2]
j=1: 1<=2 -> i=1, swap arr[1] with arr[1] -> [2,1,2]
then swap arr[i+1]=arr[2] with arr[2] -> no change. Return index2.
So the pivot ends at index2, and the left part is indices0 and1: [2,1]. So the duplicate 2 at index0 is in the left part. So the right part is empty. But in our case, for even n, we are taking min of arr[k1+1:]. If k1=0, then arr[1:] is [1,2]? Wait, in this example, n=3? Not even.
For even n, after quickselect for k1, the pivot at index k1 is the k1-th smallest. The left part has indices 0 to k1-1, which are k1 elements. The right part has indices k1+1 to n-1. So the right part has n - (k1+1) elements. For n=4, k1=1, so right part has 2 elements. For n=2, k1=0, right part has 1 element. So the right part is never empty.
But what if all elements are the same? Then after quickselect for k1, the array might be partitioned such that the left part is empty? Let's see:
n=4, k1=1. Array [5,5,5,5].
quickselect for k1=1:
Suppose pivot_index=0. Partition:
move pivot to end: swap arr[0] with arr[3] -> [5,5,5,5] (same).
i=-1
j=0: 5<=5 -> i=0, swap arr[0] with arr[0] -> [5,5,5,5]
j=1: 5<=5 -> i=1, swap arr[1] with arr[1] -> [5,5,5,5]
j=2: 5<=5 -> i=2, swap arr[2] with arr[2] -> [5,5,5,5]
then swap arr[i+1]=arr[3] with arr[3] -> no change. Return index3.
Since pivot index3 > k1=1, recurse on left part (0 to 2).
In subarray [5,5,5] (indices0,1,2), look for k=1.
pivot_index=1. Partition:
move pivot to end: swap arr[1] with arr[2] -> [5,5,5]
i=-1
j=0: 5<=5 -> i=0, swap -> [5,5,5]
then swap arr[i+1]=arr[1] with arr[2] -> [5,5,5] (same). Return index2.
Since pivot index2 > k=1, recurse on left part (0 to 1).
In subarray [5,5] (indices0,1), look for k=1.
pivot_index=1. Partition:
move pivot to end: swap arr[1] with arr[1] -> no change.
i=-1
j=0: 5<=5 -> i=0, swap -> [5,5]
then swap arr[i+1]=arr[1] with arr[1] -> no change. Return index1.
Now k=1 == pivot_index=1, return arr[1]=5.
So after quickselect, the array might be [5,5,5,5] and the element at index1 is 5. The left part (index0) is [5] and the right part (indices2,3) are [5,5]. So m2 = min([5,5]) = 5. Then median = (5+5)/2=5. Correct.
So it works.
Therefore, the algorithm is:
If n is odd: use quickselect to find the element at index n//2.
If n is even: use quickselect to find the element at index n//2 - 1, then the median is the average of that element and the minimum of the elements from index n//2 to the end.
But note: in the even case, we are taking the minimum of arr[k1+1:], which is from index k1+1 to the end. And k1 = n//2 -1, so k1+1 = n//2. So we are taking the minimum of the second half? But the second half may not be sorted. But we know that all elements in the second half are >= arr[k1]. And the smallest element in the second half is the k2-th smallest.
So the code is as above.
Now, explain the algorithm:
We use the Quickselect algorithm to find the kth smallest element. Quickselect is a selection algorithm that finds the kth smallest element in an unordered list. It is related to the quicksort sorting algorithm. It works by choosing a pivot and partitioning the array into two parts: elements less than or equal to the pivot and elements greater than the pivot. Then, based on the position of the pivot, it recursively searches in the appropriate part.
For an odd number of elements, the median is the middle element, which is the (n//2)th smallest (0-indexed).
For an even number of elements, the median is the average of the two middle elements. We can find the first middle element (at index n//2 - 1) using Quickselect. Then, due to the partitioning, the second middle element (at index n//2) is the smallest element in the right part (from index n//2 to the end) because all elements in the right part are greater than or equal to the first middle element and the first middle element is the largest among the first n//2 elements? Actually, after Quickselect for the first middle element, the array is partitioned such that the first n//2 elements (0 to n//2-1) are the smallest n//2 elements (but not sorted), and the element at index n//2-1 is the (n//2-1)th smallest. The next smallest (the n//2th) is the smallest element in the right part.
Therefore, we can compute the median as the average of the (n//2-1)th smallest and the minimum of the right part.
Time complexity:
If we sort the list first, the time complexity is O(n log n).
Using Quickselect, the average time complexity is O(n). The worst-case time complexity of Quickselect is O(n^2) if we choose bad pivots, but by choosing a random pivot we make the worst-case unlikely. The min operation on the right part is O(n) in the worst case, but on average the right part has size about n/2, so it's O(n). Therefore, the overall average time complexity is O(n).
We can achieve O(n) worst-case by using the median-of-medians algorithm to choose the pivot, but that is more complex and has a larger constant factor.
So we can do better than sorting.
Final note: the function returns a float for even n because we divide by 2.0. For odd n, it returns an integer if the list contains integers? But the problem says list of integers, but median might be float for even n. So we return float for even and integer for odd? Actually, in Python, dividing by 2.0 gives float. We can return integer for odd if we want, but the problem doesn't specify. We'll return integer for odd and float for even.
But note: if the list has an odd number of elements and we return an integer, that's fine. For even, we return float.
Alternatively, we can always return float.
I'll adjust to return float for even and for odd return the element which might be integer. But the problem says "list of integers", so the median might be non-integer for even. So it's okay.
Let's write the final code.
However, note: the quickselect function as written above modifies the array. But we are working on a copy, so the original list is not changed.
We can also avoid copying if we are allowed to modify the input. But the problem doesn't specify, so we copy.
One more thing: what if the list has one element? Then n is odd, and we return that element.
What if the list has two elements? Then n is even, k1=0, we run quickselect for k=0, which returns the minimum. Then we take min of arr[1:], which is the maximum. Then average.
Example: [2,1]
quickselect for k=0:
might choose pivot=1 (index1). Partition:
move pivot to end: swap arr[1] with arr[1] -> no change.
i=-1
j=0: 2<=1? No.
then swap arr[i+1]=arr[0] with arr[1] -> [1,2]. Return index0.
So m1 = arr[0] = 1.
arr[1:] = [2], min=2.
median = (1+2)/2=1.5.
Correct.
So the code should work.
Let me write the final answer.
To find the median of a list of integers, we can use the Quickselect algorithm, which efficiently finds the k-th smallest element. The median is the middle element when the list is sorted. For an odd-length list, it's the element at index n//2 (0‑indexed). For an even‑length list, it's the average of the elements at indices n//2 - 1 and n//2.
Approach
-
Quickselect: A selection algorithm based on the partitioning step of Quicksort. It works as follows:
- Choose a random pivot and partition the array into elements ≤ pivot and > pivot.
- After partitioning, the pivot is in its final sorted position.
- Recurse on the left or right subarray depending on whether the target index is less than or greater than the pivot index.
- Average time complexity: O(n); worst‑case: O(n²) (unlikely with random pivots).
-
Median Calculation:
- Odd
n: Directly return the element at index n//2 via Quickselect.
- Even
n:
- Find the element at index
k1 = n//2 - 1 with Quickselect. This element is the k1‑th smallest.
- Due to partitioning, all elements from index
k1+1 onward are ≥ arr[k1]. The next smallest element (at index k2 = n//2) is the minimum of this right part.
- Return the average of
arr[k1] and that minimum.
Solution Code
import random
def partition(arr, low, high, pivot_index):
pivot = arr[pivot_index]
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
def quickselect(arr, k, low=0, high=None):
if high is None:
high = len(arr) - 1
if low == high:
return arr[low]
pivot_index = random.randint(low, high)
pivot_index = partition(arr, low, high, pivot_index)
if k == pivot_index:
return arr[k]
elif k < pivot_index:
return quickselect(arr, k, low, pivot_index-1)
else:
return quickselect(arr, k, pivot_index+1, high)
def median(nums):
if not nums:
return None
n = len(nums)
arr = nums.copy()
if n % 2 == 1:
k = n // 2
return quickselect(arr, k)
else:
k1 = n // 2 - 1
m1 = quickselect(arr, k1)
m2 = min(arr[k1+1:])
return (m1 + m2) / 2.0
Explanation
- Partitioning: Moves a randomly chosen pivot to the end, then rearranges elements so that all ≤ pivot are on the left and > pivot on the right. The pivot is then placed in its final position and that index is returned.
- Quickselect: Recursively narrows down the search to the side containing the desired index
k. When the pivot lands at k, we've found the k‑th smallest element.
- Median Handling:
- For odd
n, Quickselect directly gives the median.
- For even
n, after finding the lower median (k1‑th smallest), the upper median is the minimum of the right partition because all elements there are ≥ the lower median and the smallest among them is the next in order.
Complexity Analysis
- Sorting first: O(n log n) time, O(1) or O(n) extra space depending on sort.
- Quickselect approach:
- Average time: O(n) — each partition reduces the problem size roughly by half.
- Worst‑case time: O(n²) — occurs with consistently poor pivot choices (mitigated by randomization).
- Space: O(1) extra (in‑place partitioning) plus recursion stack O(log n) on average.
Using Quickselect improves the average time from O(n log n) to O(n), which is optimal for this problem. The worst‑case can be reduced to O(n) with the median‑of‑medians pivot selection, but the constant factors are higher, so randomization is practical.