Photo Contest Podium

MediumsortingAlso known as Kth Largest Element in an Array

A town runs an online photo contest. Each photo's score is upvotes minus downvotes, so a disliked photo can score below zero. The scores arrive in no particular order.

The organisers announce prizes one place at a time, and today they only need the score that takes place k. Sorting thousands of scores just to read off one of them is more work than the job needs.

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 highest: 27, 27, 18, 14, 9, 3. Two photos tie on 27, so places 1 and 2 are both 27.

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 from highest to lowest and return the one at index k - 1. It is correct and short, and costs O(n log n).

Sorting puts every score in its exact place, but you only need one place. Quickselect does a partition, keeps one side, and the work shrinks roughly by half each time: n + n/2 + n/4 + … ≈ 2n steps on average.

A min-heap that keeps only the k biggest scores seen so far is another good answer, at O(n log k). It shines 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