Heaps Top K
409. K-th Smallest Element with a Heap
You are given an array of integers nums and an integer k. Return the k-th smallest element of nums.
The k-th smallest element is the one in position k when nums is sorted from smallest to largest,
counting from 1. Equal values take separate places, so in [1,4,4] the second and the third smallest are
both 4.
Example 1
Input: nums = [6, -3, 8, 1, -3, 5, 0], k = 3
0Explanation: From smallest to largest the elements are −3, −3, 0, 1, 5, 6, 8. The two −3s take the first two places, so the third smallest is 0.
Example 2
Input: nums = [4, 15, 9, 15], k = 4
15Explanation: From smallest to largest the elements are 4, 9, 15, 15. When k equals the length of the array, the
answer is the largest element.
Example 3
Input: nums = [9, 4, 1000000000, -1000000000], k = 1
-1000000000Explanation: With k = 1 the answer is the smallest element.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ k ≤ nums.length
Clarifying questions
What you would ask an interviewer before writing any code.