Selection · Medium
A ranking service needs one order statistic from an unsorted batch. Sorting the entire batch is unnecessary. Duplicate values occupy separate positions in the descending order.
Return the kth largest entry with k counted from one, or null when k is outside the valid range.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "nums": number[], "k": number }.
Fields
- nums contains signed integer values. k is an integer rank.
Output
Return value
- Return a number or null. Duplicates count as separate entries.
- If k < 1 or k > nums.length return null.
- Do not mutate nums; partition a private copy if needed.
Constraints
- At most 100000 values, each an integer in [-1000000000,1000000000].
- -100000 <= k <= 100001.
- Use expected linear selection rather than fully sorting. Randomized pivots or a correct worst-case linear selection are allowed.
Examples
Example 1
{
"k": 2,
"nums": [
4,
1,
4,
2
]
}Returns
4The two 4 entries occupy ranks 1 and 2.
Example 2
{
"k": 3,
"nums": [
2,
7
]
}Returns
nullThe rank is too large.
Required complexity
O(n) expected time and O(n) space for a non-mutating copy