3.4 KiB
3.4 KiB
id | title | challengeType | forumTopicId |
---|---|---|---|
587d825b367417b2b2512c8b | Remove an Element from a Max Heap | 1 | 301710 |
Description
- Move the last element in the heap into the root position.
- If either child of the root is greater than it, swap the root with the child of greater value.
- Continue swapping until the parent is greater than both children or you reach the last level in the tree.
Instructions
remove
. This method should return the greatest value that has been added to our max heap and remove it from the heap. It should also reorder the heap so the heap property is maintained. After removing an element, the next greatest element remaining in the heap should become the root.
Tests
tests:
- text: The MaxHeap data structure should exist.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() }; return (typeof test == 'object')})());
- text: MaxHeap should have a method called print.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.print == 'function')})());
- text: MaxHeap should have a method called insert.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.insert == 'function')})());
- text: MaxHeap should have a method called remove.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; return (typeof test.remove == 'function')})());
- text: The remove method should remove the greatest element from the max heap while maintaining the max heap property.
testString: assert((function() { var test = false; if (typeof MaxHeap !== 'undefined') { test = new MaxHeap() } else { return false; }; test.insert(30); test.insert(300); test.insert(500); test.insert(10); let result = []; result.push(test.remove()); result.push(test.remove()); result.push(test.remove()); result.push(test.remove()); return (result.join('') == '5003003010') })());
Challenge Seed
var MaxHeap = function() {
this.heap = [null];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)] && index > 1) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
}
this.heap = arr;
}
this.print = () => {
return this.heap.slice(1);
}
// Only change code below this line
// Only change code above this line
};
Solution
// solution required