![]() |
VOOZH | about |
Given an integer array arr[] and k. Find the k'th smallest element in the given array.
Note: k is always smaller than the size of the array.
Examples:
Input: arr[] = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4
Output: 5
Explanation: 4th smallest element in the given array is 5.Input: arr[] = [7, 10, 4, 3, 20, 15], k = 3
Output: 7
Explanation: 3rd smallest element in the given array is 7.
Table of Content
The idea is to sort the given array and return the element at the index k - 1.
5
The idea is to maintain a max heap of size k while iterating through the array. The heap always contains the k smallest elements seen so far. If the heap size exceeds k, remove the largest element. At the end, the heap holds the k smallest elements.
5
The main idea is to use QuickSelect to find the k-th largest element by picking a pivot and partitioning the array so that all elements greater than the pivot are on the left and smaller ones on the right. If the pivot ends up at index k–1, it is the k-th largest element. Otherwise, we recursively search only in the left or right part that contains the k-th largest element.
5
Time Complexity : O(n2) in the worst case, but on average works in O(n log n) time and performs better than priority queue based algorithm.
Auxiliary Space : O(n) for recursion call stack in worst case. On average : O(log n)
The main idea is to use counting sort’s frequency counts to track how many elements are smaller or equal to each value, and then directly identify the K'th smallest element from these cumulative counts without fully sorting the array.
Note: This approach is particularly useful when the range of elements is small, this is because we are declaring a array of size maximum element. If the range of elements is very large, the counting sort approach may not be the most efficient choice.
5
Time Complexity: O(n + maxElement), where maxElement is the maximum element of the array.
Auxiliary Space: O(maxElement)