DEV Community

Anjana R.K.
Anjana R.K.

Posted on

Kth Smallest Element in an Array

Hi everyone!
While practicing array problems, I came across this question about finding the kth smallest element. It’s a good problem for understanding sorting and indexing.

Problem
Given an array and a number 'k', we need to find the kth smallest element.

Example:
Input: [7, 10, 4, 3, 20, 15], k = 3

Output: 7

My Approach
At first, I thought about checking all elements manually, but that would be complicated.

Then I realized:

If we sort the array, the kth smallest element will be at index 'k-1'.
So the solution becomes very simple.

Logic

  • Sort the array
  • Return the element at position'k-1'

Code (Python)
class Solution:
def kthSmallest(self, arr, k):
arr.sort()
return arr[k - 1]

Time & Space Complexity

  • Time: O(n log n) (due to sorting)
  • Space: O(1)

What I Learned

  • Sorting can simplify many problems
  • Indexing is important when working with ordered data
  • Always think of a simple approach first before optimizing

Thanks for reading!
Feel free to share better approaches or optimizations.

Top comments (0)