Problem 319483 · medium · Phase 03 Linear Management & Searching

Top-K Players Including Ties

sorting · ties · filtering · multi-key sort

Given players, a list of (name, score) tuples, and an integer k, return the names of the players who make the top k, with ties included: sort the scores in descending order, let cut be the k-th score in that order, and return every player whose score is >= cut.

Order the returned names by score descending, then by name ascending. If k <= 0 return []; if k >= len(players) return everyone.

Examples

Input:  players = [("ann", 50), ("bob", 70), ("cat", 50), ("dan", 90), ("eve", 50)], k = 2
Output: ["dan", "bob"]
Input:  players = [("ann", 50), ("bob", 70), ("cat", 50), ("dan", 90), ("eve", 50)], k = 3
Output: ["dan", "bob", "ann", "cat", "eve"]
Explanation: The 3rd highest score is 50 and three players share it, so all of them are included.

Constraints

  • 0 <= len(players) <= 10**5, names are distinct lowercase strings
  • Target complexity: O(n log n).

Goals

  • Determine the cut-off score from a sorted copy
  • Include everybody who reaches the cut-off, even beyond k entries
  • Order the result by score descending and name ascending
Starting Python…