Photo Contest Podium

MediumsortingAlso known as Kth Largest Element in an Array

A town runs an online photo contest. Each photo scores upvotes minus downvotes, so a score can be below zero. Scores arrive in no particular order.

The organisers announce prizes one place at a time, and today they need only the score in place k. Sorting thousands of scores to read off one is more work than needed.

Your task

Write kthMostVotes(scores, k). Return the k-th largest value in scores, where k = 1 means the largest. Equal scores each take their own place: in [8, 8, 3] the 2nd largest is 8, not 3.

Aim for O(n) on average. You may copy the list, but do not sort it.

kthMostVotes(scores: int[], k: int) → int

Examples

Example 1
Input
scores = [14, 3, 27, 9, 27, 18]
k = 2
Output
27
Why

In order from the highest, the scores are 27, 27, 18, 14, 9 and 3, and the two 27s take places 1 and 2.

Example 2
Input
scores = [14, 3, 27, 9, 27, 18]
k = 3
Output
18
Why

Places 1 and 2 are the two 27s, so place 3 is 18. Removing duplicates first would wrongly give 14.

Constraints

  • 1 ≤ scores.length ≤ 10,000
  • -1,000,000 ≤ scores[i] ≤ 1,000,000
  • 1 ≤ k ≤ scores.length
Start with brute force

Sort the scores highest first and return index k - 1. This is short and correct, and it runs in O(n log n).

Sorting places every score, but you need one place. Quickselect partitions, keeps one side, and the work roughly halves each time: n + n/2 + n/4 + … ≈ 2n steps on average.

A min-heap of the k biggest scores seen so far is another good answer, at O(n log k). It is the better choice when scores arrive as a stream.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code