SORT-P4

The k-th fastest

Practice 4 of 6Sorting8 tests

The problem

The list a holds journey times. Return the value that would be at index k (counting from 0) if the list were sorted. Do not change a. sorted(), .sort() and heapq are switched off.

kth_smallest([29, 10, 14, 37, 13, 5, 33, 18, 21], 4)   # 18
kth_smallest([4, 9, 1, 7], 0)                          # 1

The tests include a list that is already sorted and a list where every value is the same.

Limits

  • Up to 500,000 values. k is at least 0 and less than len(a).

Builds on SORT-3 Quick sort and partitioning and SORT-8 Quickselect.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1MiddleNot run
2Smallest and largestNot run
3RepeatsNot run
4One valueNot run
5300,000 values in orderNot run
6300,000 equal valuesNot run
7500,000 mixed valuesNot run
8Input not changedNot run