Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Kth smallest element in an unsorted array

Moderate
0/80
Average time to solve is 15m
profile
Contributed by
23 upvotes
Asked in companies
Paytm (One97 Communications Limited)DelhiveryFlipkart

Problem statement

Given an unsorted array ‘arr’ of distinct integers and an integer ‘k’, your task is to find the ‘k-th’ smallest element in the array.

Example:
n = 5, k = 2 and arr[] = {6, 5, 4, 8, 7}
The array elements in sorted order are [4, 5, 6, 7, 8]. The ‘2-nd’ smallest element in the array is 5, so the answer is 5.
Note:
1. Don’t print anything. Return the value of ‘k-th’ smallest element.
2. ‘k’ is a positive integer and not greater than the size of the array.
3. The array ‘arr’ is unsorted, and all the elements of the array are distinct.
Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 10
1 <= n <= 1000
1 <= k <= n
-10^6 <= arr[i] <=10^6

Where ‘T’ is the total number of test cases, ‘n’ denotes the array’s size, ‘k’ denotes the ‘k-th’ smallest element that you must return, and ‘arr[i]’ denotes the range of elements in the array.

Time limit: 1 second

Sample input 1:

2
5 3
1 2 3 4 5
5 4
1 3 2 6 5

Sample output 1:

3
5

Explanation of sample input 1:

Test Case 1:
The array elements in sorted order are [1, 2, 3, 4, 5]. The ‘3-rd’ smallest element in the array is 3, so the answer is 3.

Test Case 2:
The array elements in sorted order are [1, 2, 3, 5, 6]. The ‘4-th’ smallest element in the array is 5, so the answer is 5.

Sample input 2:

2
5 1
10 23 45 8 21
6 6
20 10 30 40 60 50

Sample output 2:

8
60
Full screen
Console