Prepin
Log in

Locate the K'th smallest element in an array.

Approach / Explanation

This question requires you to create a method or function that can identify the K'th smallest element in an array. The function should return the K’th smallest number from the array, with K being provided as an input or argument. For example, if the array is [5, 7, 1, 3, 2] and K is 2, the K'th smallest element would be 2, since when sorted in ascending order, the second element is 2. Keep in mind that most programming languages use zero-based indexing for arrays, so you will need to consider this in your solution. Key points to remember include: Understanding how to traverse or search through an array. Knowing how to sort an array in ascending order. Recognizing that arrays typically start at index 0 rather than 1.

Suggested Answer

A solution to this issue is to initially sort the array in ascending order, and then return the element located at the (K-1)-th index. Below is the corresponding Python code: def findKthSmallest ( arr , K ) : arr . sort ( ) return arr [ K - 1 ] In this code, the function findKthSmallest accepts two parameters: the array arr and the integer K . It first sorts the array in ascending order by invoking the sort method. Subsequently, it returns the K'th smallest element by accessing the element at the (K-1)th index from the sorted array.

Alternative Answer

Using a binary search algorithm would be a more efficient approach if the array is sorted, or a priority queue (such as a min heap in Java) if the array is unsorted. Below is a Java example demonstrating the use of a priority queue: import java . util . PriorityQueue ; public int findKthSmallest ( int [ ] nums , int k ) { PriorityQueue < Integer > queue = new PriorityQueue < > ( ) ; for ( int num : nums ) { queue . add ( num ) ; } for ( int i = 0 ; i < k - 1 ; i ++ ) { queue . poll ( ) ; } return queue . peek ( ) ; } In this Java code, the method findKthSmallest accepts an array nums and an integer k as inputs. It creates a priority queue and fills it with the elements from the array. The method then removes the top element from the queue k - 1 times. Consequently, the topmost element remaining in the queue will be the K'th smallest element, which is returned using queue.peek() . This approach is effective because Java's priority queue is implemented as a min heap, which sorts elements in ascending order.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.