-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkth-largest-element-in-a-stream.js
More file actions
75 lines (63 loc) · 1.86 KB
/
kth-largest-element-in-a-stream.js
File metadata and controls
75 lines (63 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Problem: Kth Largest Element in a Stream
* Link: https://leetcode.com/problems/kth-largest-element-in-a-stream/
* Difficulty: Easy
*
* Design a class to find the kth largest element in a stream.
*
* Time Complexity: O(n log k) init, O(log k) per add
* Space Complexity: O(k)
*/
// JavaScript Solution - Min Heap of size k
class KthLargest {
constructor(k, nums) {
this.k = k;
this.heap = []; // min-heap
for (const num of nums) this.add(num);
}
add(val) {
this.heap.push(val);
this._bubbleUp(this.heap.length - 1);
// Keep only k largest elements
if (this.heap.length > this.k) {
this.heap[0] = this.heap.pop();
this._sinkDown(0);
}
return this.heap[0]; // min of k largest = kth largest
}
_bubbleUp(i) {
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (this.heap[parent] <= this.heap[i]) break;
[this.heap[parent], this.heap[i]] = [this.heap[i], this.heap[parent]];
i = parent;
}
}
_sinkDown(i) {
const n = this.heap.length;
while (true) {
let smallest = i;
const left = 2 * i + 1, right = 2 * i + 2;
if (left < n && this.heap[left] < this.heap[smallest]) smallest = left;
if (right < n && this.heap[right] < this.heap[smallest]) smallest = right;
if (smallest === i) break;
[this.heap[smallest], this.heap[i]] = [this.heap[i], this.heap[smallest]];
i = smallest;
}
}
}
module.exports = KthLargest;
/* Python Solution:
import heapq
class KthLargest:
def __init__(self, k, nums):
self.k = k
self.heap = [] # min-heap of size k
for num in nums:
self.add(num)
def add(self, val):
heapq.heappush(self.heap, val)
if len(self.heap) > self.k:
heapq.heappop(self.heap) # remove smallest
return self.heap[0] # kth largest
*/