DEV Community

Santhoshi Mary A
Santhoshi Mary A

Posted on

Task – Find the Kth Smallest Element in an Array

Problem Statement

Given an integer array arr[] and an integer k,
find and return the kth smallest element in the array.

The kth smallest element is determined based on the sorted order of the array.

Example 1

Input:

arr[] = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10]
k = 4

Output:

5

Explanation:

If we sort the array:

[2, 3, 4, 5, 6, 10, 10, 33, 48, 53]

The 4th smallest element is 5.

Example 2

Input:

arr[] = [7, 10, 4, 3, 20, 15]
k = 3

Output:

7

Explanation:

Sorted array:

[3, 4, 7, 10, 15, 20]

The 3rd smallest element is 7.

Constraints
1 ≤ arr.size() ≤ 10^5
1 ≤ arr[i] ≤ 10^5
1 ≤ k ≤ arr.size()
Approach 1 – Sorting Method (Simple and Clear)
Logic
Sort the array in ascending order.
Return the element at index k-1.

Why k-1?

Because Python uses 0-based indexing.

Time Complexity: O(n log n)
Space Complexity: O(1) (if sorting in place)

SOLUTION:
class Solution:
def kthSmallest(self, arr, k):
arr.sort()
return arr[k - 1]
Explanation of Code
arr.sort() sorts the array in ascending order.
arr[k - 1] gives the kth smallest element.
We subtract 1 because indexing starts from 0.

Top comments (0)