1
// TC: O(klogk + (n-k)logk) => O(nlogk) | SC: O(k)2
var findKthLargest = function (nums, k) {3
const minHeap = new MinHeap();5
// add k elements, one-by-one to heap6
// TC: O(klogk) | SC: O(k)7
for (let i = 0; i < k; i++) {11
// loop remaining elements12
// TC: O((n-k)logk) time13
for (let j = k; j < nums.length; j++) {14
// pop smaller element, and push larger element15
if (nums[j] > minHeap.peek()) {17
minHeap.push(nums[j]);19
// otherwise, do nothing22
return minHeap.peek();31
// add node to end of heap33
// find correct position of node38
let currIdx = this.heap.length - 1,39
parentIdx = Math.floor((currIdx - 1) / 2);40
while (currIdx > 0 && this.heap[parentIdx] > this.heap[currIdx]) {41
// swap values, and set new currIdx and parentIdx42
this.swap(currIdx, parentIdx);44
parentIdx = Math.floor((currIdx - 1) / 2);49
const min = this.heap[0];50
// assign top node to last node to retain complete binary tree property51
this.heap[0] = this.heap[this.heap.length - 1];52
// pop last node and find correct position of top node60
leftIdx = currIdx * 2 + 1,62
const heapLen = this.heap.length;64
while (leftIdx < heapLen) {65
// calc right child node66
let rightIdx = leftIdx + 1;69
if (rightIdx < heapLen && this.heap[rightIdx] < this.heap[leftIdx])71
else idxToSwap = leftIdx;73
// compare smaller child node to curr node74
if (this.heap[currIdx] <= this.heap[idxToSwap]) break;76
// otherwise, swap vals and set new currIdx and leftIdx77
this.swap(currIdx, idxToSwap);79
leftIdx = currIdx * 2 + 1;84
[this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];92
return this.heap.length;