K’th Least Element in a Min-Heap

Given a min-heap of size n, find the kth least element in the min-heap.

Examples:

Input : {10, 50, 40, 75, 60, 65, 45}
k = 4
Output : 50



Input : {10, 50, 40, 75, 60, 65, 45}
k = 2
Output : 40

Naive approach:
We can extract the minimum element from the min-heap k times and the last element extracted will be the kth least element. Each deletion operations takes O(log n) time, so the total time complexity of this approach comes out to be O(k * log n).

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find k-th smallest
// element in Min Heap.
#include <bits/stdc++.h>
using namespace std;
  
// Structure for the heap
struct Heap {
    vector<int> v;
    int n; // Size of the heap
  
    Heap(int i = 0)
        : n(i)
    {
        v = vector<int>(n);
    }
};
  
// Generic function to
// swap two integers
void swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}
  
// Returns the index of
// the parent node
inline int parent(int i)
{
    return (i - 1) / 2;
}
  
// Returns the index of
// the left child node
inline int left(int i)
{
    return 2 * i + 1;
}
  
// Returns the index of
// the right child node
inline int right(int i)
{
    return 2 * i + 2;
}
  
// Maintains the heap property
void heapify(Heap& h, int i)
{
    int l = left(i), r = right(i), m = i;
    if (l < h.n && h.v[i] > h.v[l])
        m = l;
    if (r < h.n && h.v[m] > h.v[r])
        m = r;
    if (m != i) {
        swap(h.v[m], h.v[i]);
        heapify(h, m);
    }
}
  
// Extracts the minimum element
int extractMin(Heap& h)
{
    if (!h.n)
        return -1;
    int m = h.v[0];
    h.v[0] = h.v[h.n-- - 1];
    heapify(h, 0);
    return m;
}
  
int findKthSmalles(Heap &h, int k)
{
    for (int i = 1; i < k; ++i)
        extractMin(h);
    return extractMin(h);
}
  
int main()
{
    Heap h(7);
    h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
    int k = 2;
    cout << findKthSmalles(h, k);
    return 0;
}

chevron_right


Output:

40

Time Complexity: O(k * log n)

Efficient approach:
We can note an interesting observation about min-heap. An element x at ith level has i – 1 ancestors. By the property of min-heaps, these i – 1 ancestors are guaranteed to be less than x. This implies that x cannot be among the least i – 1 elements of the heap. Using this property, we can conclude that the kth least element can have a level of at most k.

We can reduce the size of the min-heap such that it has only k levels. We can then obtain the kth least element by our previous strategy of extracting the minimum element k times. Note that the size of the heap is reduced to a maximum of 2k – 1, therefore each heapify operation will take O(log 2k) = O(k) time. The total time complexity will be O(k2). If n >> k, then this approach performs better than the previous one.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find k-th smallest
// element in Min Heap using k levels
#include <bits/stdc++.h>
using namespace std;
  
// Structure for the heap
struct Heap {
    vector<int> v;
    int n; // Size of the heap
  
    Heap(int i = 0)
        : n(i)
    {
        v = vector<int>(n);
    }
};
  
// Generic function to
// swap two integers
void swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}
  
// Returns the index of
// the parent node
inline int parent(int i)
{
    return (i - 1) / 2;
}
  
// Returns the index of
// the left child node
inline int left(int i)
{
    return 2 * i + 1;
}
  
// Returns the index of
// the right child node
inline int right(int i)
{
    return 2 * i + 2;
}
  
// Maintains the heap property
void heapify(Heap& h, int i)
{
    int l = left(i), r = right(i), m = i;
    if (l < h.n && h.v[i] > h.v[l])
        m = l;
    if (r < h.n && h.v[m] > h.v[r])
        m = r;
    if (m != i) {
        swap(h.v[m], h.v[i]);
        heapify(h, m);
    }
}
  
// Extracts the minimum element
int extractMin(Heap& h)
{
    if (!h.n)
        return -1;
    int m = h.v[0];
    h.v[0] = h.v[h.n-- - 1];
    heapify(h, 0);
    return m;
}
  
int findKthSmalles(Heap &h, int k)
{
    h.n = min(h.n, int(pow(2, k) - 1));
    for (int i = 1; i < k; ++i)
        extractMin(h);
    return extractMin(h);
}
  
int main()
{
    Heap h(7);
    h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
    int k = 2;
    cout << findKthSmalles(h, k);
    return 0;
}

chevron_right


Output:

40

Time Complexity: O(k2)

More efficient approach:
We can further improve the time complexity of this problem by the following algorithm:

  1. Create a priority queue P (or Min Heap) and insert the root node of the min-heap into P. The comparator function of the priority queue should be such that the least element is popped.
  2. Repeat these steps k – 1 times:
    1. Pop the least element from P.
    2. Insert left and right child elements of the popped element. (if they exist).
  3. The least element in P is the kth least element of the min-heap.

The initial size of the priority queue is one, and it increases by at most one at each of the k – 1 steps. Therefore, there are maximum k elements in the priority queue and the time complexity of the pop and insert operations is O(log k). Thus the total time complexity is O(k * log k).

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find k-th smallest
// element in Min Heap using another
// Min Heap (Or Priority Queue)
#include <bits/stdc++.h>
using namespace std;
  
// Structure for the heap
struct Heap {
    vector<int> v;
    int n; // Size of the heap
  
    Heap(int i = 0)
        : n(i)
    {
        v = vector<int>(n);
    }
};
  
// Returns the index of
// the left child node
inline int left(int i)
{
    return 2 * i + 1;
}
  
// Returns the index of
// the right child node
inline int right(int i)
{
    return 2 * i + 2;
}
  
int findKthSmalles(Heap &h, int k)
{
    // Create a Priority Queue
    priority_queue<pair<int, int>,
                   vector<pair<int, int> >,
                   greater<pair<int, int> > >
        p;
  
    // Insert root into the priority queue
    p.push(make_pair(h.v[0], 0));
  
    for (int i = 0; i < k - 1; ++i) {
        int j = p.top().second;
        p.pop();
        int l = left(j), r = right(j);
        if (l < h.n)
            p.push(make_pair(h.v[l], l));
        if (r < h.n)
            p.push(make_pair(h.v[r], r));
    }
  
    return p.top().first;
}
  
int main()
{
    Heap h(7);
    h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
    int k = 4;
    cout << findKthSmalles(h, k);
    return 0;
}

chevron_right


Output:

50

Time Complexity: O(k * log k)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : vaibhav29498