DEV Community

Navin S
Navin S

Posted on

๐ŸŽฏ Find the Kth Smallest Element in an Array

Finding the kth smallest element is a common and important problem in data structures and algorithms.
It appears frequently in coding interviews and competitive programming.


๐Ÿ“Œ Problem Statement

Given an array arr[] and an integer k, return the kth smallest element in the array.

๐Ÿ‘‰ The kth smallest element is based on the sorted order of the array.


๐Ÿ” Examples

Example 1:

Input:  arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4
Output: 5
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input:  arr = [7, 10, 4, 3, 20, 15], k = 3
Output: 7
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Concept

If we sort the array, the kth smallest element will be at index:

k - 1
Enter fullscreen mode Exit fullscreen mode

But sorting takes O(n log n) time.

๐Ÿ‘‰ We can do better using a Heap (Priority Queue).


๐Ÿ”„ Approach: Using Max Heap (Efficient)

We maintain a max heap of size k.

Step-by-Step:

  1. Create an empty max heap
  2. Iterate through the array:
  • Add element to heap
  • If heap size > k โ†’ remove the largest element

    1. After processing all elements:
  • The root of heap = kth smallest element


๐Ÿ’ป Python Code (Heap)

```python id="w7o3ka"
import heapq

def kth_smallest(arr, k):
max_heap = []

for num in arr:
    heapq.heappush(max_heap, -num)  # use negative for max heap

    if len(max_heap) > k:
        heapq.heappop(max_heap)

return -max_heap[0]
Enter fullscreen mode Exit fullscreen mode

Example

print(kth_smallest([7, 10, 4, 3, 20, 15], 3))




---

## ๐Ÿงพ Dry Run (Step-by-Step)

For:



```id="s9xzq7"
arr = [7, 10, 4, 3, 20, 15], k = 3
Enter fullscreen mode Exit fullscreen mode

Heap process:

  • Add 7 โ†’ [7]
  • Add 10 โ†’ [10, 7]
  • Add 4 โ†’ [10, 7, 4]
  • Add 3 โ†’ remove 10 โ†’ [7, 4, 3]
  • Add 20 โ†’ remove 20 โ†’ [7, 4, 3]
  • Add 15 โ†’ remove 15 โ†’ [7, 4, 3]

๐Ÿ‘‰ Answer = 7


โšก Time and Space Complexity

  • Time Complexity: O(n log k)
  • Space Complexity: O(k)

๐Ÿ” Alternative Approach: Sorting

```python id="j18s6n"
def kth_smallest(arr, k):
arr.sort()
return arr[k - 1]




* Time: `O(n log n)`
* Simpler but less efficient

---

## ๐Ÿš€ Bonus: Quickselect (Advanced)

* Average Time: `O(n)`
* Worst Case: `O(nยฒ)`
* Used in advanced interview questions

---

## ๐Ÿงฉ Where Is This Used?

* Order statistics
* Data analysis
* Ranking systems
* Interview problems

---

## ๐Ÿ Conclusion

The **max heap approach** is the most efficient and widely used method when dealing with kth smallest problems under constraints.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)