Implement randomized Quickselect without k-shift bug
Company: Meta
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of randomized Quickselect and selection algorithms, including in-place partition semantics for the k-th largest element, careful index and k-update reasoning to prevent k-shift/off-by-one bugs, handling duplicates and adversarial pivots, and analysis of expected versus worst-case time and auxiliary space.
Constraints
- 1 <= nums.length <= 10^5
- 1 <= k <= nums.length
- -10^9 <= nums[i] <= 10^9
- Array may contain duplicates
- k is 1-based (k = 1 means the maximum, k = n means the minimum)
Examples
Input: ([3, 2, 1, 5, 6, 4], 2)
Expected Output: 5
Explanation: Sorted descending: [6,5,4,3,2,1]; the 2nd largest is 5.
Input: ([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
Expected Output: 4
Explanation: Descending with duplicates: [6,5,5,4,3,3,2,2,1]; the 4th largest is 4.
Input: ([1], 1)
Expected Output: 1
Explanation: Single element; the 1st largest is the only element.
Input: ([7, 7, 7, 7], 3)
Expected Output: 7
Explanation: All duplicates; every order statistic equals 7.
Input: ([-1, -5, -3, -2, -4], 1)
Expected Output: -1
Explanation: All negatives; the largest (k=1) is -1.
Input: ([-1, -5, -3, -2, -4], 5)
Expected Output: -5
Explanation: All negatives; the 5th largest (k=n) is the minimum, -5.
Input: ([5, 4, 3, 2, 1], 5)
Expected Output: 1
Explanation: Already sorted descending (adversarial for fixed pivots); k=n returns the minimum, 1.
Input: ([2, 1], 1)
Expected Output: 2
Explanation: Two-element array; the 1st largest is 2.
Hints
- Partition so that elements strictly greater than the pivot land to its left; then the pivot's 1-based rank within [left..right] is rank = p - left + 1.
- On the right branch you only recurse when k > rank, so k' = k - rank is always >= 1 — never write rank - k (that produces a negative target).
- Pick the pivot index uniformly at random each iteration to avoid O(n^2) on sorted/adversarial inputs; the iterative loop keeps auxiliary space at O(1).
- To find the k-th SMALLEST instead, either flip the comparison in partition (move LESS-than elements left) or call this routine with k' = n - k + 1.