Kth Smallest Element in an Unsorted Array

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.

Input:

The first line of 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, where n is the array's size.
The second line of each test case contains n space-separated integers denoting the array elements.

Output:

For each test case, return the k-th smallest element in the array.
Output for each query is printed in a separate line.

Example:

Input:
n = 5, k = 2 and arr[] = {6, 5, 4, 8, 7}
Output:
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.

Constraints:

  • 1 <= T <= 10
  • 1 <= n <= 1000
  • 1 <= k <= n
  • -10^6 <= arr[i] <= 10^6

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.
AnswerBot
13d

Find the k-th smallest element in an unsorted array of distinct integers.

  • Sort the array and return the k-th element.

  • Use a priority queue or quickselect algorithm for efficient solution.

  • Handle edge cas...read more

Help your peers!
Add answer anonymously...
Flipkart Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter