DEV Community

Suruthika
Suruthika

Posted on

CA 07 - Kth Smallest

Problem
Kth Smallest
You are given an integer array arr[] and an integer k.
Your task is to find the kth smallest element in the array.

The kth smallest element is based on the sorted order of the array.
Input: [10, 5, 4, 3, 48, 6, 2, 33, 53, 10], k = 4 → Output: 5
Input: [7, 10, 4, 3, 20, 15], k = 3 → Output: 7

Approach

The simplest way is to sort the array and pick the kth element.

Steps:
Sort the array in ascending order
Return the element at index k - 1

This works because sorting arranges elements from smallest to largest.

Complexity:

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

def kthSmallest(arr, k):
    arr.sort()
    return arr[k - 1]
arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10]
k = 4
print(kthSmallest(arr, k))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)