DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

FINDING THE Kth SMALLEST ELEMENT IN A ARRAY

Finding the Kth Smallest Element in a Python Array – Simple & Efficient
Working with arrays in Python often comes down to searching, sorting, and finding specific elements. One common interview question is:
How do you find the kth smallest element in an unsorted array?
Here’s a straightforward approach using Python.
Understanding the Problem
Suppose you have an array like this:
Python
arr = [7, 10, 4, 3, 20, 15]
And you want to find the 3rd smallest element.
Step by step, the sorted version of this array is:
Python
[3, 4, 7, 10, 15, 20]
The 3rd smallest element is 7.
Python Solution
Python makes this task super simple thanks to its built-in sorting functionality. Here's a neat function to do it:

Python
class Solution:
def kthSmallest(self, arr, k):
# Step 1: Sort the array in ascending order
arr.sort() # Python's sort() uses Timsort, very efficient O(n log n)

    # Step 2: Return the element at index k-1
    return arr[k-1]  # Arrays are 0-indexed
Enter fullscreen mode Exit fullscreen mode

How It Works
Sorting the Array
The sort() method arranges all elements in ascending order. Python uses Timsort, a hybrid of merge sort and insertion sort. It has a time complexity of O(n log n) and is very efficient in practice.
Finding the kth Element
Python arrays are 0-indexed, which means the first element is at index 0.
To get the kth smallest, we access arr[k-1].
Example Usage
Python
arr = [7, 10, 4, 3, 20, 15]
k = 3

solution = Solution()
print(solution.kthSmallest(arr, k))
Output:
7

Why This Approach Works
Simplicity: Python’s built-in sort() does the heavy lifting.
Efficiency: O(n log n) time is acceptable for most practical scenarios.
Readability: Just two lines of code after defining the function.
Alternatives for Large Data
If your array is huge and performance is critical, consider:
Heap-based approach: Using a min-heap to avoid sorting the whole array.**
Quickselect algorithm: Average O(n) time complexity.**

Key Takeaways
Python’s built-in sorting is powerful and often the best choice for clarity and efficiency.
Remember the 0-indexing when accessing elements.
Always check if k is within the valid range to avoid errors.
This solution is perfect for quick coding, or just learning how sorting can simplify complex problems.

Top comments (0)