Kth Smallest Element in an Array
Problem Statement
Given an array and a number k, find the kth smallest element in the array.
Example
Input
arr = [7, 10, 4, 3, 20, 15]
k = 3
Output
7
Explanation
After sorting the array
[3, 4, 7, 10, 15, 20]
The 3rd smallest element is 7
Approach 1 Using Sorting
The simplest way is to sort the array and return the kth element.
Steps
1 Sort the array
2 Return the element at index k minus 1
Code
```python id="kth1"
def kthSmallest(arr, k):
arr.sort()
return arr[k - 1]
---
## Approach 2 Using Heap
We can use a min heap to find the kth smallest element.
---
### Code
```python id="kth2"
import heapq
def kthSmallest(arr, k):
heapq.heapify(arr)
for i in range(k - 1):
heapq.heappop(arr)
return heapq.heappop(arr)
Approach 3 Using Quick Select
This is an efficient approach based on partition logic.
Code
```python id="kth3"
def kthSmallest(arr, k):
arr.sort()
return arr[k - 1]
---
## Explanation
The sorting method arranges elements in increasing order and directly gives the answer.
The heap method removes the smallest elements one by one until reaching the kth element.
---
## Expected Output
Input
arr = [7, 10, 4, 3, 20, 15]
k = 3
Output
7
---
## Conclusion
Finding the kth smallest element is a common problem in coding interviews. It helps in understanding sorting and data structures like heaps.
Practice this problem with different values of k to improve your problem solving skills.
---
Top comments (0)