DEV Community

Jarvish John
Jarvish John

Posted on • Edited 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 main objective was to understand how sorting changes the positions of elements in a list and how that can help in identifying elements based on their rank, like the k-th element. I also focused on learning how to directly access elements after sorting without overcomplicating the approach. Instead of using advanced or optimized techniques, I wanted to keep the solution simple, clear, and easy to understand, especially from a beginner’s perspective, prioritizing readability and logic over complexity.

Solution

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

Idea:
Sort the array in ascending order. The kth 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 from smallest to largest
Since indexing starts at 0:
1st smallest is index 0
2nd smallest is index 1
kth smallest is index k-1
Print the element at index k-1

Top comments (0)