Kth Smallest Element

Easy
0/40
Average time to solve is 15m
profile
Contributed by
45 upvotes
Asked in companies
SnapdealMicrosoftMedia.net

Problem statement

You are given an array of integers 'ARR' of size 'N' and another integer 'K'.


Your task is to find and return 'K'th smallest value present in the array.


Note: All the elements in the array are distinct.


Example
If 'N' is 5 and 'K' is 3 and the array is 7, 2, 6, 1, 9

Sorting the array we get 1, 2, 6, 7, 9

Hence the 3rd smallest number is 6.
Detailed explanation ( Input/output format, Notes, Images )
Input format
The first line contains two space-separated integers ‘N’ representing the size of the array and ‘K’.

The second line contains 'N' space-separated integers that represent elements of the array 'ARR'.
Output format
Print a single line that contains a single integer which is the 'Kth' smallest element of the array.
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Sample Input 1:
7 5
5 9 1 8 10 6 4 
Sample Output 1:
8
Explanation of Input 1:
Sorted array will be 1 4 5 6 8 9 10, this shows that 8 is the fifth-smallest element in the array.
Sample Input 2:
7 2
24 8 23 28 3 1 19 
Sample Output 2:
3
Constraints:
1 <= N <=10 ^ 4
1 <= K <= N
1 <= ARR[i] <= 10 ^ 9

Time limit: 1 sec.
Hint

Try to think of a way where you can change elements of ARR in such a way that you are able to get Kth smallest element directly in O(1)

Approaches (3)
Brute Force
  1. Sort the elements of ‘ARR’ using function ‘SORT’
  2. Return element at ('K' - 1)th index
Time Complexity

O(N * logN) where ‘N’ is the number of elements in the array.

 

As we are sorting the array which takes O(N * log(N)) time.

Space Complexity

O(1).

 

Since we are not using any extra space.

Code Solution
(100% EXP penalty)
Kth Smallest Element
Full screen
Console