oneby7

Heaps Top K

409. K-th Smallest Element with a Heap

Medium

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

Output: 0

Explanation: 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

Output: 15

Explanation: 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

Output: -1000000000

Explanation: With k = 1 the answer is the smallest element.

Check your understanding

Work out the answer for this input before you write any code.

nums = [8, 2, 11, 2, 6, 4, 15], k = 3

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.