Problem 377546 · medium · Phase 03 Linear Management & Searching

Kth Largest Distinct Value

sorting · sets · indexing

Given a list of integers nums and a positive integer k, return the k-th largest distinct value. Duplicates count once: in [5, 5, 4] the 2nd largest distinct value is 4.

If there are fewer than k distinct values, return None.

Examples

Input:  nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Input:  nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Output: 3
Explanation: The distinct values in descending order are 6, 5, 4, 3, 2, 1.
Input:  nums = [1, 1], k = 2
Output: None

Constraints

  • 0 <= len(nums) <= 10**5, 1 <= k <= 10**5
  • Target complexity: O(n log n).

Goals

  • Remove duplicates before ranking values
  • Index into a descending sorted list safely
  • Return None when the request cannot be satisfied
Starting Python…