DEV Community

Mohith
Mohith

Posted on

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
Enter fullscreen mode Exit fullscreen mode

If I arrange the array in sorted order:

[2, 3, 4, 5, 6, 10, 10, 33, 48, 53]
Enter fullscreen mode Exit fullscreen mode

Now the 4th smallest element becomes:

5
Enter fullscreen mode Exit fullscreen mode

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

  1. Sort the array
  2. Access the element at index k - 1
  3. 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
Enter fullscreen mode Exit fullscreen mode

Code (Java)

import java.util.*;

class Solution {
    public int kthSmallest(int[] arr, int k) {
        Arrays.sort(arr);
        return arr[k - 1];
    }
}
Enter fullscreen mode Exit fullscreen mode

Why This Works

  • Sorting arranges elements in increasing order
  • The kth smallest element will always be at position k - 1
  • The approach is simple and easy to implement

Complexity Analysis

  • Time Complexity: O(n log n)
  • Space Complexity: O(1)

Final Thought

This problem shows that understanding the requirement clearly can lead to a simple solution.
Instead of overthinking, identifying that “kth smallest” depends on ordering helps in solving it directly.


Top comments (0)