DEV Community

Jarvish John
Jarvish John

Posted on

CA 07 - Kth Smallest

Problem Statement

Given an integer array arr[] and an integer k, your task is to find and return the kᵗʰ smallest element in the given array.

Note: The kᵗʰ smallest element is determined based on the sorted order of the array.

Examples:

Input: arr[] = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4
Output: 5
Explanation: 4th smallest element in the given array is 5.

Input: arr[] = [7, 10, 4, 3, 20, 15], k = 3
Output: 7
Explanation: 3rd smallest element in the given array is 7.

My Goal

For this problem, my goal was to:

Understand how sorting affects element positioning
Learn how to access elements based on rank (k)
Keep the solution simple and beginner-friendly
Focus on clarity over complex optimizations

Solution

I used a sorting-based approach, which is the simplest way to solve this problem.

Idea:
Sort the array in ascending order
The kᵗʰ smallest element will be at index k-1

This works because sorting arranges elements from smallest to largest.

Solution Code (Python)

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

a.sort()
print(a[k - 1])
Enter fullscreen mode Exit fullscreen mode

Explanation
First, sort the array → smallest to largest
Since indexing starts at 0:
1st smallest → index 0
2nd smallest → index 1
kᵗʰ smallest → index k-1
Print the element at index k-1

Top comments (0)