allizwell.jobsdoor360.in

Kth Largest and Smallest Element

Data Structures and Algorithms / Heaps / Kth Largest and Smallest Element

Kth Largest and Smallest Element in an Array

Finding the Kth largest and Kth smallest elements is a common problem in Data Structures and Algorithms. Given an array and an integer K, we need to find the element that occupies the Kth position when the array is arranged in ascending or descending order. Heaps provide an efficient way to solve these problems without completely sorting the array.

1. What Is the Kth Largest Element?

The Kth largest element is the element that appears at position K when the array is arranged in descending order.

For example, consider the array:

10, 40, 20, 50, 30

After arranging the elements in descending order:

50, 40, 30, 20, 10

The largest element is 50, the second largest is 40, and the third largest is 30.

Example:

Array: 10, 40, 20, 50, 30

K = 3

Answer = 30

2. What Is the Kth Smallest Element?

The Kth smallest element is the element that appears at position K when the array is arranged in ascending order.

Consider the same array:

10, 40, 20, 50, 30

After arranging the elements in ascending order:

10, 20, 30, 40, 50

Example:

Array: 10, 40, 20, 50, 30

K = 2

Answer = 20

3. Understanding Kth Largest and Smallest

Let us understand the positions of elements using a simple table.

Position Ascending Order Descending Order
1st 10 50
2nd 20 40
3rd 30 30
4th 40 20
5th 50 10

Notice that the Kth smallest element is at position K in ascending order, while the Kth largest element is at position K in descending order.

4. Approach 1: Sorting

The simplest approach is to sort the array and directly access the required position.

For Kth Smallest Element

Sort the array in ascending order. The Kth smallest element will be at index K - 1.

For Kth Largest Element

Sort the array in descending order. The Kth largest element will be at index K - 1.

C++ Program: Kth Smallest Using Sorting

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {

    vector<int> arr = {10, 40, 20, 50, 30};

    int k = 2;

    sort(arr.begin(), arr.end());

    cout << "Kth Smallest Element: "
         << arr[k - 1];

    return 0;
}

Output

Kth Smallest Element: 20

C++ Program: Kth Largest Using Sorting

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {

    vector<int> arr = {10, 40, 20, 50, 30};

    int k = 3;

    sort(arr.begin(), arr.end(), greater<int>());

    cout << "Kth Largest Element: "
         << arr[k - 1];

    return 0;
}

Output

Kth Largest Element: 30

Complexity Analysis

  • Time Complexity: O(N log N)
  • Space Complexity: Depends on the sorting implementation; standard C++ sorting uses O(log N) auxiliary stack space on typical implementations.
Limitation: Sorting the entire array may do more work than necessary when we only need one element. A Heap can solve the problem more efficiently when K is small compared with N.

5. Approach 2: Min Heap for Kth Largest Element

A Min Heap is useful for finding the Kth largest element. We maintain a Min Heap containing only K elements.

The steps are:

  1. Create an empty Min Heap.
  2. Insert the first K elements into the Min Heap.
  3. For every remaining element, compare it with the root.
  4. If the current element is greater than the root, remove the root and insert the current element.
  5. After processing all elements, the root is the Kth largest element.

Why Do We Use a Min Heap?

We want to keep the K largest elements seen so far. The smallest among those K elements should be at the root. Whenever a larger element appears, we replace that smallest element.

At the end, the root represents the Kth largest element.

C++ Program

#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int kthLargest(vector<int>& arr, int k) {

    priority_queue<int, vector<int>, greater<int>> pq;

    for (int num : arr) {

        pq.push(num);

        if (pq.size() > k) {
            pq.pop();
        }
    }

    return pq.top();
}

int main() {

    vector<int> arr = {10, 40, 20, 50, 30};

    int k = 3;

    cout << "Kth Largest Element: "
         << kthLargest(arr, k);

    return 0;
}

Output

Kth Largest Element: 30

6. Dry Run: Kth Largest Using Min Heap

Consider:

Array = [10, 40, 20, 50, 30]

K = 3

We maintain a Min Heap of maximum size 3.

Current Element Heap Elements Action
10 10 Insert 10
40 10, 40 Insert 40
20 10, 40, 20 Insert 20
50 20, 40, 50 Remove 10 and insert 50
30 30, 40, 50 Remove 20 and insert 30

At the end, the Min Heap contains the three largest elements:

30, 40, 50

The smallest element among these three is 30. Therefore, the third largest element is 30.

7. Approach 3: Max Heap for Kth Smallest Element

A Max Heap can be used to find the Kth smallest element. We maintain a Max Heap containing only K elements.

The steps are:

  1. Create an empty Max Heap.
  2. Insert the first K elements.
  3. For every remaining element, compare it with the root.
  4. If the current element is smaller than the root, remove the root and insert the current element.
  5. After processing all elements, the root is the Kth smallest element.

Why Do We Use a Max Heap?

We want to keep the K smallest elements. The largest among those K elements should remain at the root.

Whenever a smaller element appears, we replace the root. At the end, the root is the Kth smallest element.

C++ Program

#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int kthSmallest(vector<int>& arr, int k) {

    priority_queue<int> pq;

    for (int num : arr) {

        pq.push(num);

        if (pq.size() > k) {
            pq.pop();
        }
    }

    return pq.top();
}

int main() {

    vector<int> arr = {10, 40, 20, 50, 30};

    int k = 2;

    cout << "Kth Smallest Element: "
         << kthSmallest(arr, k);

    return 0;
}

Output

Kth Smallest Element: 20

8. Dry Run: Kth Smallest Using Max Heap

Consider:

Array = [10, 40, 20, 50, 30]

K = 2

We maintain a Max Heap containing only two elements.

Current Element Heap Elements Action
10 10 Insert 10
40 10, 40 Insert 40
20 10, 20 Remove 40 and insert 20
50 10, 20 Ignore 50
30 10, 20 Ignore 30

The final Max Heap contains the two smallest elements:

10, 20

The root contains 20, which is the second smallest element.

9. Time and Space Complexity of Heap Approaches

Let N represent the number of elements in the array and K represent the required position.

Operation Time Complexity
Insert an element into Heap O(log K)
Remove the root O(log K)
Process all N elements O(N log K)
Read the final root O(1)

Overall Time Complexity:

O(N log K)

Space Complexity:

O(K)

The Heap stores at most K elements, so the extra space required is O(K).

10. Handling Duplicate Elements

Duplicate values are counted as separate elements in the standard Kth largest and Kth smallest problem unless the question explicitly asks for distinct elements.

Example:

Array = [5, 3, 5, 2, 1]

Sorted Array = [1, 2, 3, 5, 5]

2nd largest element = 5

2nd smallest element = 2

Important: Always check whether the problem asks for the Kth element including duplicates or the Kth distinct element. These are different problems and may require different logic.

11. Kth Largest Distinct Element

If a problem asks for the Kth largest distinct element, duplicate values must be ignored.

One simple approach is to use a set to remove duplicates, then sort the unique values in descending order.

C++ Program

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;

int main() {

    vector<int> arr = {5, 3, 5, 2, 1};

    int k = 2;

    set<int, greater<int>> uniqueElements;

    for (int num : arr) {
        uniqueElements.insert(num);
    }

    if (k > uniqueElements.size()) {
        cout << "Not enough distinct elements";
        return 0;
    }

    auto it = uniqueElements.begin();

    advance(it, k - 1);

    cout << "Kth Largest Distinct Element: "
         << *it;

    return 0;
}

Output

Kth Largest Distinct Element: 3

12. Sorting vs Heap Approach

Sorting Approach Heap Approach
Sorts the complete array. Maintains only K relevant elements.
Time complexity is O(N log N). Time complexity is O(N log K).
Simple to understand and implement. Useful when K is much smaller than N.
May require modifying the array. Can process values using an additional Heap.

13. Common Mistakes

  • Confusing the Kth largest element with the element at index K in an unsorted array.
  • Forgetting that array indexing starts from zero.
  • Using a Max Heap for Kth largest without understanding why a Min Heap of size K is more suitable.
  • Using a Min Heap for Kth smallest without understanding why a Max Heap of size K is more suitable.
  • Forgetting to remove elements when Heap size becomes greater than K.
  • Ignoring duplicate values when the problem counts them.
  • Not checking whether K is valid for the given array.
  • Assuming the internal Heap array is completely sorted.

14. Important Interview Questions

Q1. What is the Kth largest element?

It is the element at position K when the array is arranged in descending order.

Q2. What is the Kth smallest element?

It is the element at position K when the array is arranged in ascending order.

Q3. Which Heap is used to find the Kth largest element efficiently?

A Min Heap of size K is commonly used.

Q4. Which Heap is used to find the Kth smallest element efficiently?

A Max Heap of size K is commonly used.

Q5. What is the time complexity of the Heap approach?

O(N log K), where N is the number of elements and K is the required position.

Q6. What is the space complexity of the Heap approach?

O(K), because the Heap stores at most K elements.

Q7. Why is a Min Heap used for Kth largest?

It keeps the K largest elements and places the smallest among them at the root. That root is the Kth largest element.

Q8. Why is a Max Heap used for Kth smallest?

It keeps the K smallest elements and places the largest among them at the root. That root is the Kth smallest element.

Q9. Does the standard Kth largest problem count duplicates?

Usually, yes. Unless the problem says distinct elements, duplicate values are counted separately.

Q10. When is the Heap approach better than sorting?

It is particularly useful when K is small compared with N, because it avoids sorting the entire array.

15. Practice Problems

  1. Find the 2nd largest element in an array using sorting.
  2. Find the 3rd smallest element using a Max Heap.
  3. Find the Kth largest element using a Min Heap of size K.
  4. Find the Kth smallest element using a Max Heap of size K.
  5. Find the Kth largest distinct element in an array.
  6. Find the Kth smallest distinct element in an array.
  7. Find the Kth largest element when duplicate values exist.
  8. Find the Kth smallest element in an array containing negative and positive numbers.
  9. Compare the sorting and Heap approaches for different values of N and K.
  10. Find the Kth largest element in a large array without sorting the complete array.

16. Summary

The Kth largest and Kth smallest problems ask us to find an element at a particular position in sorted order. We can solve them using sorting or Heap-based approaches.

  • Kth largest means position K in descending order.
  • Kth smallest means position K in ascending order.
  • Sorting solves the problem in O(N log N) time.
  • A Min Heap of size K finds the Kth largest element.
  • A Max Heap of size K finds the Kth smallest element.
  • The Heap approach takes O(N log K) time.
  • The Heap approach requires O(K) extra space.
  • Duplicate handling depends on the problem statement.
Key Takeaway: Remember this important relationship: use a Min Heap of size K for Kth largest, and a Max Heap of size K for Kth smallest. This technique is widely used in coding interviews and competitive programming.
Scroll to Top