
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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
- Related Articles
- Kth Largest Element in an Array in Python
- Kth Largest Element in an Array
- C++ Program to Find kth Largest Element in a Sequence
- Kth Smallest Element in a BST in Python
- Kth Smallest Element in a Sorted Matrix in Python
- Python – Find Kth Even Element
- Filter Tuples by Kth element from List in Python
- Program to find largest kth index value of one list in Python
- kth smallest/largest in a small range unsorted array in C++
- Closest Pair to Kth index element in Tuple using Python
- Python – Extract Kth element of every Nth tuple in List
- Program to find kth smallest element in linear time in Python
- Element with largest frequency in list in Python
- Program to find the kth smallest element in a Binary Search Tree in Python
- Python – Remove Rows for similar Kth column element

Advertisements