DEV Community

Haripriya V
Haripriya V

Posted on

ASSIGNMENT 7

1.k'th smallest

Problem
Given an array and a number k, find the k-th smallest element.

Example:
Id="ex2"
Input: arr = [7, 10, 4, 3, 20, 15], k = 3
Output: 7

**Approach Used: **Sorting
The simplest way:
1.Sort the array
2.Return the element at index k-1

class Solution:
def kthSmallest(self, arr, k):
arr.sort()
return arr[k-1]

Explanation
After sorting:
Id="sorted"
[3, 4, 7, 10, 15, 20]
The 3rd smallest element is:
Id="calc"
arr[k-1] → arr[2] → 7
--> Because indexing starts from 0

Complexity Analysis
Time Complexity: O(n log n) (due to sorting)
Space Complexity: O(1) (in-place sort)

Best Approach (Advanced)
--> QuickSelect Algorithm
Average Time: O(n)
Used in real systems
But:
Harder to implement
Not needed for beginners

Conclusion
Sorting is simple and works well for small inputs
For large data:
Use heap or QuickSelect
Always validate k before processing

Top comments (0)