Kth Largest Element in a Stream in Python



Suppose we want to design a class to find the kth largest element in a stream. It is the kth largest element in the sorted order, not the kth distinct element.

The KthLargest class will have a constructor which accepts an integer k and an array nums, that will contain initial elements from the stream. For each call to the method KthLargest.add, will return the element representing the kth largest element in the stream.

So, if the input is like k = 3, initial elements = [4,5,8,2], then call add(3), add(5), add(10), add(9), add(4). , then the output will be 4,5,5,8,8 respectively.

To solve this, we will follow these steps −

  • Define the initializer, This will take k, nums
    • array := nums
  • Define a function add() . This will take val
    • insert val at the end of array
    • sort the array
    • return array[size of array -k]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class KthLargest:
   def __init__(self, k, nums):
      self.array = nums
      self.k = k
   def add(self, val):
      self.array.append(val)
      self.array.sort()
      return self.array[len(self.array)-self.k]
ob = KthLargest(3, [4,5,8,2])
print(ob.add(3))
print(ob.add(5))
print(ob.add(10))
print(ob.add(9))
print(ob.add(4))

Input

ob.add(3)
ob.add(5)
ob.add(10)
ob.add(9)
ob.add(4)

Output

4
5
5
8
8
Updated on: 2020-07-04T09:44:48+05:30

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements