VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-k-smallest-elements-in-an-array/

⇱ Find k smallest elements in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find k smallest elements in an array

Last Updated : 23 Jul, 2025

Given an array arr[] and an integer k, the task is to find k smallest elements in the given array. Elements in the output array can be in any order.

Examples:

Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3
Output: [1, 2, 9]

Input: arr[] = [11, 5, 12, 9, 44, 17, 2], k = 2
Output: [2, 5]

[Approach - 1] Using Sorting

The idea is to sort the input array in ascending order, so the first k elements in the array will be the k smallest elements.


Output
1 2 9 

Time complexity: O(n * logn)
Auxiliary Space: O(1)

[Approach - 2] Using Quick Sort Partitioning Step (Quick Select Algorithm)

The idea is to use the partitioning step of QuickSort to find the k smallest elements in the array, without sorting the entire array. In the partitioning step, we rearrange the elements in a way that all elements smaller than or equal to a chosen pivot (usually the last element) are placed on its left, and all elements greater than the pivot are on its right. And pivot element in its correct sorted position.
After each partition, we compare the number of elements in the leftpart of the array (which contains all elements smaller than or equal to the pivot) with k:

  • Number of elements in the left = k, it means all elements in the left part (including pivot) are the k smallest elements.
  • Number of elements in the left > k, it means that k smallest elements exist in the left subarray only, so we recursively search in the left subarray.
  • Number of elements in the left < k, it means that the k smallest elements include the entire left part of the array along with some elements from the right part. Therefore we reduce k by the number of elements already covered on the left side and search in the right subarray.

Output
1 2 9 

Time Complexity: O(n*n) in worst case(O(n) on average)
Auxiliary Space: O(n)

[Approach - 3] Using Priority Queue(Max-Heap)

The idea is, as we iterate through the array, we keep track of the k smallest elements at each step. To achieve this, we use a max-heap. First, we insert the initial k elements into the max-heap. After that, for each next element, we compare it with the top of the heap. Since the top element of the max-heap is the largest among the k elements, if the current element is smaller than the top, it means the top element is no longer one of the k smallest elements. In this case, we remove the top and insert the smaller element. After completing the entire traversal, the heap will contain exactly the k smallest elements of the array.


Output
9 2 1 

Time Complexity: O(n * log(k))
Auxiliary Space: O(k)

Comment
Article Tags: