Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Goal: Sort with one line, then read the answer off an index.

Your language already sorts

Think of a teacher lining up a class by height. You don't need to write that routine yourself, because every language has a fast sort built in. It takes about n times log n steps, so even a million numbers sort in well under a second.

In Python it is a list method, in Java it is Arrays.sort, and in C++ it is sort. One line, and the list runs from smallest to largest.

Sorting is one line: in every language, so use it.
JavaScript: sorts as text unless you give it a compare function, so 10 would come before 9.
In code
nums = [6, 3, 8, 1]
nums.sort()
# [1, 3, 6, 8]
Sort [9, 4, 7, 1, 6], then find the 3rd smallest
9
0
4
1
7
2
1
3
6
4
i

Before sorting, the 3rd smallest could be anywhere.

Move 1 of 4

In a sorted list, position is rank

Once the class is lined up, the shortest child is first, the second shortest is next, and so on. The same is true of a sorted list: the smallest value sits at position 0, the 2nd smallest at position 1.

So the kth smallest sits at position k − 1. Repeats count once each time they appear: in 2, 2, 5 the 2nd smallest is 2.

After sorting: the kth smallest is just a lookup.
k counts from 1, but positions count from 0.
In code
prices.sort()
cheapest = prices[0]
second = prices[1]