Finding the Kth Smallest Element in an Array
Source: Dev.to
What I Did
I created a function called kth_smallest that takes two inputs:
- an array of numbers
- a value
k(which represents the position)
Example
Input: [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4
Output: 5
This means the 4th smallest number in the array is 5.
How I Solved It
To solve this problem, I first sorted the array in ascending order. After sorting, the smallest element comes first, then the second smallest, and so on.
Since array indexing starts from 0, the kth smallest element will be at position k‑1.
So after sorting, I simply returned the element at index k‑1.
Code
def kth_smallest(arr, k):
arr.sort()
return arr[k-1]
print(kth_smallest([10, 5, 4, 3, 48, 6, 2, 33, 53, 10], 4))
print(kth_smallest([7, 10, 4, 3, 20, 15], 3))
How It Works
Once the array is sorted, the position of each element becomes fixed based on its value. Sorting makes it easy to directly pick the kth smallest element using its index, avoiding the need for multiple manual comparisons.