DEV Community

Dharani
Dharani

Posted on

Kth Smallest

Introduction

Finding the Kth smallest element in an array is a common problem in data structures. It is useful in many real-world applications like ranking and statistics.


Problem Statement

Given an array of integers and a number k, find the Kth smallest element in the array.


Approach 1: Sorting

  1. Sort the array in ascending order
  2. Return the element at index k-1

Python Code (Sorting)


python
def kth_smallest(arr, k):
    arr.sort()
    return arr[k - 1]

# Example
arr = [7, 10, 4, 3, 20, 15]
k = 3
print("Kth Smallest:", kth_smallest(arr, k))


## Input
arr = [7, 10, 4, 3, 20, 15]
k = 3

## output
   7
Enter fullscreen mode Exit fullscreen mode

Top comments (0)