AlgoMaster Logo

Kth Largest Element in a Stream

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force with Sorting

Intuition:

For each addition of a new element into the stream, we can sort the elements and fetch the k-th largest element directly. This approach is straightforward but inefficient for larger inputs.

Steps:

  1. Maintain a list of numbers that we will continually update as new numbers are added.
  2. Every time a new number is added, insert it into the list.
  3. Sort the list in descending order.
  4. Retrieve the k-th element from the sorted list.

Code:

2. Sorted List

Intuition:

Maintain a sorted list at all times and ensure the list is sorted with each new insertion. This results in better time complexity than re-sorting the entire list.

Steps:

  1. Maintain a list of numbers, sorted after each insertion.
  2. Use binary search to find the position where the new element should be inserted to keep the list sorted.
  3. After insertion, directly access the k-th largest element.

Code:

3. Min-Heap (Optimal)

Intuition:

Use a min-heap of size k to efficiently manage the k-th largest element. The min-heap will allow the smallest element to be on top, ensuring we can easily access the k-th largest element by maintaining heap size.

Steps:

  1. Use a PriorityQueue (min-heap) of size k.
  2. Iterate over the initial list and add each element to the heap.
  3. If the heap exceeds size k, remove the smallest element (top of the heap).
  4. For a new addition, add the element and ensure the heap does not exceed size k.
  5. The top element of the heap will be the k-th largest element.

Code: