Kth Smallest Element
Problem
You’re given an array of integers and an integer k, and need to find the kth smallest element in the array.
Strategy
At first, it feels like you need something complex to track the kth element.
But since the kth smallest element is based on sorted order, I thought about it differently:
What if I just sort the array first?
So the idea is simple:
- Sort the array
- Return the element at index
k - 1
Because indexing starts from 0.
Code
class Solution:
def kthSmallest(self, arr, k):
arr.sort()
return arr[k - 1]
Key Lines Explained
arr.sort()
Sorts the array in ascending order.
return arr[k - 1]
Since arrays are 0-indexed, the kth smallest element will be at index k - 1.
Why This Works
Once the array is sorted:
- Smallest element → index 0
- 2nd smallest → index 1
- kth smallest → index k-1
So the answer becomes direct.
Complexity
Time: O(n log n)
Space: O(1)
Final Note
This is the most straightforward approach.
Even though there are more optimized solutions (like heaps or quickselect), sorting keeps it simple and easy to understand.
Top comments (0)