Skip to content

Kth Smallest Element

MediumPython 3ArraysSorting

You are given an unsorted list of integers nums and an integer k. Return the k-th smallest element (1-indexed): the value that would sit at index k - 1 if the list were sorted. Duplicates count individually.

Sorting solves it in O(n log n); as a follow-up, quickselect brings the average down to O(n).

Constraints:
  - 1 <= k <= len(nums)
  - values may repeat and may be negative
Examples:
  kth_smallest([7, 2, 9, 4], 1)     == 2    # the minimum
  kth_smallest([7, 2, 9, 4], 4)     == 9    # the maximum
  kth_smallest([3, 1, 3, 2], 3)     == 3    # duplicates count separately
  kth_smallest([5], 1)              == 5

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…