Problem Statement
Given an array and a number K where K is smaller than size of array, we need to find the K'th smallest element and K'th largest element in the given array. It is given that all array elements are not distinct.
Note:
If element is not present, then return -1.
K'th largest and smallest element in the sorted array. You are given an array consisting of N non distinct positive integers and a number K, your task is to find the K'th largest and K'th smallest element in the array.
1) Kth largest and smallest element in an array is the K'th element of the array when sorted in increasing order. For example consider the array {2,1,5,6,3,8} and K=3, the sorted array will be {1,2,3,5,6,8}, and the 3rd largest element will be 5 and smallest will be 3.
2) All the elements of the array are not distinct.
The first line of the input contains an integer T denoting the number of test cases.
The first line of each test case contains two space-separated integers N and K, as described in the problem statement.
The second line of each test case contains N space-separated integers, representing the elements of the array.
The only line of output prints the K'th largest and K'th smallest element separated by space.
Constraints:
1 <= T <= 100
1 <= N <= 10^3
1 <= arr[i] <= 10^9
1 <= K < N
Sample Input 1:
1
3 2
1 2 3
Sample Output 1:
2 2
Explanation For Sample Input 1:
2 is the second largest and second smallest element in an array {1,2,3}.
Sample Input 2:
1
3 2
5 5 5
Sample Output 2:
-1 -1
Explanation For Sample Input 2:
Since there is only 1 unique element therefore second largest and second smallest element does not exist hence -1.
def kthSmallestLargest(arr,k):
lis=list(set(arr))
lis.sort()
if len(lis)<k:
return [-1,-1]
else:
return [lis[k-1],lis[-k]]
#Your code goees here.
#Driver's code
t = int(input())
while t > 0:
n,k = map(int,input().split())
arr = [int(i) for i in input().split()]
small,large = kthSmallestLargest(arr,k)
print(large,small)
t -= 1
Comments
Post a Comment