The problem
Return the value that would be at position k if values were sorted, with 0 <= k < n. Use median of medians to choose pivots, so that the method is O(n) even on the worst lists.
select([7, 2, 9, 4, 1], 2) # 4
select([5, 1, 5, 1, 5, 3], 3) # 5
The tests pass the larger lists' values as special number objects that count every comparison made with them (<, <=, >, >=; == is not counted). They behave like normal numbers, and max() and min() count too. Return the values you were given, not copies made with int().
- On every list, your method may make at most 20n comparisons.
- The comparisons per value must stay flat as the list grows: for a list 32 times longer, at most 25% more per value. Sorting fails this, because it makes about log₂ n comparisons per value.
sorted(), .sort(), heapq and the functions of random are switched off. Lists of 5 values or fewer can be sorted by hand (insertion sort).
Limits
- Up to 64,000 values. Lists may be sorted, reversed, all equal, or built to beat a simple pivot rule.
Builds on DVCQ-6 Median of medians.
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
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | The smallest | Not run | |
| 3 | The largest | Not run | |
| 4 | Repeats | Not run | |
| 5 | One value | Not run | |
| 6 | Negatives, 13 values | Not run | |
| 7 | 20,000 in order | Not run | |
| 8 | 20,000 in reverse order | Not run | |
| 9 | 20,000 equal values | Not run | |
| 10 | Built against the middle pivot | Not run | |
| 11 | 20,000 scattered values | Not run | |
| 12 | Comparisons per value stay flat | Not run |