LeetCode 703: Kth Largest Element in a Stream Solution

Master LeetCode problem 703 (Kth Largest Element in a Stream), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can use a Min Heap to store the kth largest elements. We will maintain the size of the heap as k, and whenever a new element is added to the stream, we compare it with the root of the heap. If the new element is greater than the root, we remove the root and add the new element to the heap. This way, the heap will always contain the kth largest elements, and the root will be the kth largest element in the stream. Solution

Solution Code

import java.util.PriorityQueue;

class KthLargest {
    private PriorityQueue<Integer> minHeap;
    private int k;

    public KthLargest(int k, int[] nums) {
        this.k = k;
        minHeap = new PriorityQueue<>(k);
        for (int num : nums) {
            add(num);
        }
    }

    public int add(int val) {
        if (minHeap.size() < k) {
            minHeap.offer(val);
        } else if (val > minHeap.peek()) {
            minHeap.poll();
            minHeap.offer(val);
        }
        return minHeap.peek();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 703 (Kth Largest Element in a Stream)?

This page provides optimized solutions for LeetCode problem 703 (Kth Largest Element in a Stream) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 703 (Kth Largest Element in a Stream)?

The time complexity for LeetCode 703 (Kth Largest Element in a Stream) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 703 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 703 in Java, C++, or Python.

Back to LeetCode Solutions