Kth Largest Element in a Stream

Kth Largest Element in a Stream: Design and Implementation

The Kth Largest Element in a Stream problem requires designing a system to dynamically track the k-th largest integer in a stream of numbers.

This task demands an efficient approach to handle frequent updates while maintaining the k-th largest element in near real-time.

Kth largest elements

Problem: 

Design a class to find the kth largest integer in a stream of values, including duplicates. E.g. the 2nd largest from [1, 2, 3, 3] is 3. The stream is not necessarily sorted.

Implement the following methods:

  • constructor(int k, int[] nums) Initializes the object given an integer and the stream of integers nums.
  • int add(int val) Adds the integer val to the stream and returns the kth largest integer in the stream.

Problem Breakdown

Task

  1. Initialization:

    • Create a class KthLargest initialized with:
      • An integer k  representing the position of the k-th largest element.
      • An initial array nums that represents the stream of integers.
  2. Dynamic Updates:

    • A method add(val) adds a new value to the stream and returns the k-th largest element in the updated stream.

Explanation:

KthLargest kthLargest = new KthLargest(3, [1, 2, 3, 3]);
kthLargest.add(3); // return 3
kthLargest.add(5); // return 3
kthLargest.add(6); // return 3
kthLargest.add(7); // return 5
kthLargest.add(8); // return 6

Constraints:

  • 1 <= k <= 1000
  • 0 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • -1000 <= val <= 1000
  • There will always be at least k integers in the stream when you search for the kth integer.

Approach

Key Idea: Min-Heap

To efficiently track the k-th largest element, we use a min-heap of size k.

Why Min-Heap?

  1. A min-heap keeps the smallest element at the root.
  2. By maintaining a heap of size k, the root always represents the k-th largest element, as it ensures the heap contains the largest k elements of the stream.

Algorithm

Initialization

  1. Create a min-heap with the first k elements of nums.
  2. If nums has more than k elements, iterate through the remaining numbers and adjust the heap to maintain only the largest k elements.

Add Method

  1. Add the new element val to the heap.
  2. If the heap exceeds size k, remove the smallest element (heap root).
  3. Return the root of the heap, which is the k-th largest element.

There are mainly two approach to solve this problem – 

  1. Brute Force
  2. Min Heap

1. Sorting

  • Time complexity: O(m∗nlogn)
  • Space complexity: O(1) or O(n)depending on the sorting algorithm.

2. Min -Heap

Time & Space Complexity
  • Time complexity: O(m∗log⁡k)
  • Space complexity: O(k)

Where m is the number of calls made to add().

More Articles