DEV Community

Mubashir
Mubashir

Posted on

Kth Smallest

PROBLEM TO SOLVE
Given an array arr[] and an integer k, return the kth smallest element in the array.

EXAMPLE:
arr = [7, 10, 4, 3, 20, 15]
k = 3
output: 7

APPROACH USED:

  1. First, sort the array in ascending order - arr.sort()
  2. Then return the element at position k-1 - arr[k-1]

HOW IT WORKS
When we sort the array:

  1. The smallest element comes first
  2. The largest element comes last So, the kth smallest element will always be at index k-1.
class Solution:
    def kthSmallest(self, arr, k):
        arr.sort()
        return arr[k-1]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)