Skip to content
Discussion options

You must be logged in to vote

We can use a min-heap data structure. Here’s a step-by-step guide to implementing the KthLargest class using PHP:

  1. Min-Heap Data Structure: We will maintain a min-heap (priority queue) of size k. The root of this heap will always give us the k-th largest element.

  2. Initialization: During initialization, we will add the first k elements of the stream to the min-heap. For any additional elements, we will compare each new element with the smallest element in the heap (the root). If the new element is larger, we replace the smallest element with this new element and adjust the heap to maintain the k size.

  3. Adding Elements: Each time an element is added to the stream, we use the same process…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jan 23, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants