Problem 487644 · medium · Phase 04 Non-Linear Data Structures

Select the Kth Smallest by Partitioning

divide and conquer · quickselect · partitioning

A race timing system stores finishing times in arbitrary order and needs the k-th fastest time (1-indexed, duplicates count separately) without sorting everything. Write kth_fastest(times, k) returning that value. Use a partition-based recursion: pick a pivot, split the list into times below, equal to and above it, and recurse into just one part.

Examples

Input:  times = [9, 3, 7, 1, 5], k = 2
Output: 3

Input:  times = [4], k = 1
Output: 4

Constraints

  • 1 <= len(times) <= 10**4, 1 <= k <= len(times), integer times.
  • Pick the pivot as the middle element so already-sorted input does not cause deep recursion; expected O(n) time.

Goals

  • Partition around a pivot into smaller, equal and larger groups
  • Recurse into only the group that contains the answer
  • Adjust k when descending into the larger group
Starting Python…