Kth Smallest Element in an Array

Given an integer array nums and an integer k, return the kth smallest element in the array.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

You must try to solve it without sorting the array.

Example 1:

Input: nums = [3,2,1,5,6,4], k = 2

Output: 2

Explanation:

  • After sorting, the array becomes: [1,2,3,4,5,6]
  • The 2nd smallest element is 2.

Example 2:

Input: nums = [3,2,3,1,2,4,5,5,6], k = 4

Output: 3

Explanation:

  • After sorting, the array becomes: [1,2,2,3,3,4,5,5,6]
  • The 4th smallest element is 3.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [3,2,4,5,5,6], k = 4

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= nums.length <= 105
  • -104 <= nums[i] <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int kthSmallest(vector<int>& nums, int k) {
// Your code goes here
}
};
Test Case

Input:

K
Nums