Advanced topics · Exercise 95 of 100

Kth smallest or largest element

For a rank k from one through the array length, sort the values and count k positions from the small end for the kth smallest or from the large end for the kth largest. When ranking array elements, equal values each occupy a position because they are separate entries.

Try it yourself

In [7, 1, 9, 7, 3, 5], what is the fourth largest element when both copies of 7 count?

One-step hint

Draw one card per entry, including separate cards for the repeated value. Lay them out from largest to smallest and count positions from one.

Worked solution
  1. Reading from largest to smallest gives 9, 7, 7, 5, 3, 1.
  2. The two copies of 7 take positions two and three, leaving 5 in the fourth position.
DSA compiler