DEV Community

VARUN
VARUN

Posted on • Edited on

CA 07 - Kth Smallest


Problem Statement
Given:
An array arr[]
An integer k
Find the k-th smallest element.
Example:
Input: arr = [10, 5, 4, 3, 48, 6], k = 4
Output: 5

Approach Max Heap (Priority Queue)
Idea:
Keep only k smallest elements
Use a max heap of size kHow It Works

Example:

arr = [10, 5, 4, 3, 48, 6]
k = 4

Steps:

Keep pushing into heap
Maintain only 4 smallest elements
Final heap contains smallest 4
Top = answer

If a smaller element comes replace the largest in heap

Top comments (0)