Thursday, April 21, 2022

Leet Code 703. Kth Largest Element in a Stream

https://leetcode.com/problems/kth-largest-element-in-a-stream/


Example 1:

Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]

Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8


SC = O(k)

TC = O (log k) as we are storing only k elements, and up heapify will take only O(log k)


package pep.Day66;

import java.util.PriorityQueue;
import java.util.Queue;

public class LeetCode_703_Kth_Largest_Element_in_Stream {
public static void main(String[] args) {
int[] arr = {4, 5, 8, 2};
int k = 3;

KthLargest kl = new KthLargest(k, arr);
System.out.println(kl.add(3));
System.out.println(kl.add(5));
System.out.println(kl.add(10));
System.out.println(kl.add(9));
System.out.println(kl.add(4));

}

static class KthLargest {

Queue<Integer> pq;
int K;

public KthLargest(int k, int[] nums) {
K = k;
pq = new PriorityQueue<>();
for (int i : nums) {
pq.add(i);
if (pq.size() > k)
pq.remove();
}
}

public int add(int val) {
pq.add(val);
if (pq.size() > K)
pq.remove();

return pq.peek();
}
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...