KatInterview

Pick the k-th Smallest Value Without Fully Sorting

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchquickselectselectionpartitioning

Last 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 = 1 asks for the minimum, and k = len(values) asks for the maximum.
  • Duplicates are counted individually. For [1, 3, 3, 5], the 2nd and 3rd smallest values are both 3.
  • 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^5
  • 1 <= 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.