Back to articles
finding the Kth Smallest Element in an Array
How-ToCareer

finding the Kth Smallest Element in an Array

via Dev.to TutorialAshiq Omar

In this task, I worked on finding the Kth smallest element in an array. This problem is common in interviews and helps in understanding sorting and selection techniques. What I Did: I created a function kthSmallest that takes: an array arr an integer k and returns the Kth smallest element in the array. Example: Input: arr = [7, 10, 4, 3, 20, 15], k = 3 Output: 7 πŸ‘‰ Explanation: After sorting β†’ [3, 4, 7, 10, 15, 20] The 3rd smallest element is 7 How I Solved It: I used a simple sorting approach. Step-by-step approach: First, I sorted the array in ascending order Then I accessed the element at index k - 1 (because array indexing starts from 0) CODE: class Solution : def kthSmallest ( self , arr , k ): arr . sort () return arr [ k - 1 ]

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles