Problem 426827 · easy · Phase 04 Non-Linear Data Structures

Kth Smallest Distinct Value

heaps · sets · kth element

Given a list of integers nums and a positive integer k, return the k-th smallest distinct value in nums. Duplicates count once: [1, 1, 2] has only two distinct values. If nums has fewer than k distinct values return -1.

Examples

Input:  nums = [4, 1, 4, 2, 9, 1], k = 3
Output: 4
Explanation: the distinct values in ascending order are 1, 2, 4, 9; the third is 4.

Input:  nums = [5, 5, 5], k = 2
Output: -1
Explanation: there is only one distinct value.

Constraints

  • 1 <= len(nums) <= 10**5, 1 <= k <= len(nums)
  • -10**9 <= nums[i] <= 10**9
  • Target complexity: O(n log k) time after removing duplicates.

Goals

  • Collapse duplicates before ranking values
  • Pull the k smallest items out of a collection with a heap helper
  • Return a sentinel when there are not enough distinct values
Starting Python…