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:
- First, sort the array in ascending order - arr.sort()
- Then return the element at position k-1 - arr[k-1]
HOW IT WORKS
When we sort the array:
- The smallest element comes first
- 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]
Top comments (0)