Pick the k-th Smallest Value Without Fully Sorting
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Find the k-th smallest value in an unsorted integer list, counting duplicates, using a linear-time selection idea such as quickselect instead of a full sort.
You are given an unsorted list of integers values and a 1-based position k. Return the value that would sit at position k if the list were sorted in non-decreasing order.
Rules
- Positions are 1-based:
k = 1asks for the minimum, andk = len(values)asks for the maximum. - Duplicates are counted individually. For
[1, 3, 3, 5], the 2nd and 3rd smallest values are both3. - The caller's list must not be modified.
- Aim for an average running time of
O(n). A solution that simply sorts the list gives the right answers but misses the intended goal. A selection approach such as quickselect is what is wanted here.
Constraints
1 <= len(values) <= 10^51 <= k <= len(values)- Each element is an integer that fits in a 32-bit signed integer. Negative values and repeated values are allowed.
Examples
Example 1
Input: nth_smallest_value([3, 2, 1, 5, 6, 4], 2)
Output: 2
Example 2
Input: nth_smallest_value([7, 10, 4, 3, 20, 15], 3)
Output: 7
Example 3
Input: nth_smallest_value([1], 1)
Output: 1
Example 4
Input: nth_smallest_value([5, 5, 3, 3, 9, 1], 4)
Output: 5
Hints
Hint 1
Sorting works but costs O(n log n). Think about how quicksort splits the data, and ask whether you really need to process both sides of the split.
Hint 2
Partition the list around a pivot into three groups: smaller than, equal to, and larger than the pivot. Compare the 0-based rank k - 1 with the sizes of these groups to decide where the answer is.
Hint 3
If the rank falls inside the 'equal' group, the pivot itself is the answer. Otherwise recurse into just one group, adjusting the rank by the sizes of the groups you skipped. The three-way split also handles lists with many duplicates.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sorting the whole list does more work than needed, because only one position matters. Selection avoids that by discarding the part of the list that cannot contain the answer.
- Convert
kto a 0-based rankr = k - 1. - Pick a pivot and split the items into three groups:
smaller(less than the pivot),same(equal to it), andlarger(greater than it). - Compare
rwith the group sizes:- If
r < len(smaller), the answer is ther-th smallest ofsmaller. - Else if
r < len(smaller) + len(same), the answer is the pivot. - Else the answer is in
larger, at rankr - len(smaller) - len(same).
- If
- Recurse into only that one group.
The reference picks the pivot with the median-of-medians rule. It splits the items into groups of 5, takes each group's median, and recursively selects the median of those medians. This guarantees that each recursive call works on at most about 70% of the items, so the worst case is linear. Randomized quickselect, which picks a random pivot, is also fine and is O(n) on average.
Why it is correct
Every element of smaller is less than every element of same, which is less than every element of larger. So in sorted order the three groups occupy consecutive blocks, and rank r falls in exactly one of them. The three-way split is also what makes duplicates work. Equal values are removed from further recursion in a single step, so a list like [7, 7, 7, 7, 7, 7] terminates immediately instead of looping forever. Because duplicates are counted individually, the ranks line up with those of the sorted list.
The function works on a copy of the input, so the caller's list is never changed.
Complexity
- Time:
T(n) <= T(n/5) + T(7n/10) + O(n), which solves toO(n)in the worst case. With a random pivot, the expected time isO(n). - Space:
O(n)extra, since each partition builds new lists. Recursion depth isO(log n).
Reference solution
from typing import List
def nth_smallest_value(values: List[int], k: int) -> int:
data = list(values)
def select(items: List[int], rank: int) -> int:
if len(items) <= 5:
return sorted(items)[rank]
# Choose a pivot with the median-of-medians rule.
group_medians = []
for start in range(0, len(items), 5):
chunk = sorted(items[start:start + 5])
group_medians.append(chunk[len(chunk) // 2])
pivot = select(group_medians, len(group_medians) // 2)
smaller = []
same = []
larger = []
for x in items:
if x < pivot:
smaller.append(x)
elif x > pivot:
larger.append(x)
else:
same.append(x)
if rank < len(smaller):
return select(smaller, rank)
if rank < len(smaller) + len(same):
return pivot
return select(larger, rank - len(smaller) - len(same))
return select(data, k - 1)