K-th Smallest Unique Value
Practice using a sorted set (TreeSet/SortedSet) to keep values unique and in order.
Given an array of integers nums and an integer k, return the k-th smallest distinct value in nums (1-indexed). If nums has fewer than k distinct values, return -1.
This is a basics exercise for sorted, deduplicating structures like Java's TreeSet or C#'s SortedSet<T>, which keep every element unique and in sorted order automatically as you insert.
Example 1
Input: nums = [4,2,2,7,4,1], k = 2
Output: 2
Explanation: Distinct sorted values are [1,2,4,7]; the 2nd smallest is 2.
Example 2
Input: nums = [5], k = 1
Output: 5
Example 3
Input: nums = [5], k = 2
Output: -1
Explanation: Only 1 distinct value exists, so there's no 2nd.
Constraints
- 1 <= nums.length <= 1000
- -10^4 <= nums[i] <= 10^4
- 1 <= k <= 1000
Follow-up
How would you support repeatedly inserting new values and querying the k-th smallest, without re-sorting from scratch each time?
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.