DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Finding the Kth Smallest Element in an Array

Problem Statement:
Given an integer array and a value k, find the kth smallest element in the array based on sorted order.

Example:
Input: arr = [7, 10, 4, 3, 20, 15], k = 3
Output: 7

Approach:
To solve this problem, we first sort the array in ascending order. After sorting, the kth smallest element will be present at index k-1.

Code:

def kth_smallest(arr, k):
arr.sort()
return arr[k-1]

Explanation:

Sorting arranges elements from smallest to largest
Since indexing starts from 0, kth element is at position k-1

Time Complexity:
O(n log n) due to sorting

Top comments (0)