K-th Nearest Obstacle Queries - Heap [JS]
Description Solution: Heap Keep a max heap of the kth nearest obstacle distances from the origin. If the size of the heap exceeds k , we remove the furthest distance. The top of the max heap is the kth nearest obstacle at any point in time. n = length of queries Time Complexity: O(n log(k)) Space Complexity: O(k) function resultsArray(queries, k) { let heap = new Heap((a, b) => b - a); let results = []; for (let [x, y] of queries) { let dist = Math.abs(x) + Math.abs(y); heap.add(dist); if (heap.size > k) { heap.remove(); } results.push(heap.size < k ? - 1 : heap.top()); } return results; }; class Heap { constructor (comparator = ((a, b) => a - b)) { this .values = []; this .comparator = comparator; this .size = 0 ; } add( val ) { this .size++; this .values.push( val ); let idx = this .size - 1 , parentIdx = Math.floor((idx - 1 ) / 2 ); while (parentIdx >= 0 && ...