
Kth Smallest Element in an Array
My Thought Process (Java DSA) When I came across this problem, it initially looked slightly complex. Instead of directly writing code, I tried to understand what “kth smallest” actually means. Problem Statement We are given: An array of integers arr[] An integer k The task is to find the kth smallest element in the array. Initial Thinking Let’s take an example: arr = [ 10 , 5 , 4 , 3 , 48 , 6 , 2 , 33 , 53 , 10 ] k = 4 If I arrange the array in sorted order: [ 2 , 3 , 4 , 5 , 6 , 10 , 10 , 33 , 48 , 53 ] Now the 4th smallest element becomes: 5 Key Observation The term “kth smallest” directly relates to sorted order. So one straightforward approach is: Sort the array Return the element at index k - 1 Approach Sort the array Access the element at index k - 1 Return the result HOW it Runs arr = [ 7 , 10 , 4 , 3 , 20 , 15 ] k = 3 Sorted → [ 3 , 4 , 7 , 10 , 15 , 20 ] Answer → arr [ 2 ] = 7 Code (Java) import java.util.* ; class Solution { public int kthSmallest ( int [] arr , int k ) { Arr
Continue reading on Dev.to Beginners
Opens in a new tab




