diff --git a/src/data-structures/heap/Heap.js b/src/data-structures/heap/Heap.js index 45dfcfa2..938766ac 100644 --- a/src/data-structures/heap/Heap.js +++ b/src/data-structures/heap/Heap.js @@ -148,14 +148,19 @@ export default class Heap { * @return {Heap} */ remove(item, comparator = this.compare) { - // Find number of items to remove. - const numberOfItemsToRemove = this.find(item, comparator).length; + const findLastIndex = () => { + for (let index = this.heapContainer.length - 1; index >= 0; index -= 1) { + if (comparator.equal(item, this.heapContainer[index])) { + return index; + } + } - for (let iteration = 0; iteration < numberOfItemsToRemove; iteration += 1) { - // We need to find item index to remove each time after removal since - // indices are being changed after each heapify process. - const indexToRemove = this.find(item, comparator).pop(); + return -1; + }; + // We need to find item index to remove each time after removal since + // indices are being changed after each heapify process. + for (let indexToRemove = findLastIndex(); indexToRemove >= 0; indexToRemove = findLastIndex()) { // If we need to remove last child in the heap then just remove it. // There is no need to heapify the heap afterwards. if (indexToRemove === (this.heapContainer.length - 1)) {