Skip to content
BytePatterns

Kth Smallest by Partitioning

MediumSorting#quickselect#three-way-partition~30m

Problem

Given an unsorted list of integers and a number k, return the k-th smallest value, counting from 1 and counting repeated values separately. Sorting takes O(n log n) time; aim for O(n) expected time by reusing the partition step from quicksort. Leave the caller's list unchanged.

Examples

Input:  nums = [7, 2, 9, 4, 4, 1], k = 3
Output: 4
Why:    in sorted order the list reads 1, 2, 4, 4, 7, 9
Input:  nums = [3, 3, 3, 3], k = 2
Output: 3
Why:    every value equals the pivot, which must not slow the search down
Input:  nums = [5], k = 1
Output: 5
Why:    edge case, a single value

Hints

0 / 3

Stuck on the idea rather than the code? Quick Sort covers it.