In this task, I worked on finding the kth smallest element in an array. This problem is slightly different from just finding the minimum or maximum because here we need to find a specific position after sorting.
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)
For 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. So instead of manually comparing elements multiple times, sorting makes it easy to directly pick the kth smallest element using its index.
Top comments (0)