Code Logo

Priority Queue Kth Smallest

Published at25 Jul 2026
Priority Queue Easy 0 views
Like0

Find the kth smallest element in an array. Sort ascending and return the kth element. Return -1 if k exceeds array length.

Example Input & Output

Example 1
Input
[5],1
Output
5
Explanation

Single

Example 2
Input
[1,2,3],3
Output
3
Explanation

3rd smallest is max

Example 3
Input
[10,5,7],1
Output
5
Explanation

1st smallest is min

Example 4
Input
[1],2
Output
-1
Explanation

Not enough

Example 5
Input
[3,1,4,1,5],2
Output
1
Explanation

2nd smallest is 1

Algorithm Flow

Recommendation Algorithm Flow for Priority Queue Kth Smallest
Recommendation Algorithm Flow for Priority Queue Kth Smallest

Solution Approach

function solution(arr, k) {
  if (k > arr.length) return -1;
  var sorted = arr.slice().sort(function(a,b){return a-b;});
  return sorted[k-1];
}

Best Answers

java
import java.util.*;
class Solution {
    public int solution(int[] nums, int k) {
        if(k>nums.length)return -1;int[] s=nums.clone();Arrays.sort(s);return s[k-1];
    }
}