|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function maxHeapChecker(arr) take arr |
| 3 | + * which represents a heap data structure and determine whether or not it is a |
| 4 | + * max heap. A max heap has the property that all nodes in the heap are either |
| 5 | + * greater than or equal to each of its children. For example: if arr is |
| 6 | + * [100,19,36,17] then this is a max heap and your program should return the |
| 7 | + * string max. If the input is not a max heap then your program should return a |
| 8 | + * list of nodes in string format, in the order that they appear in the tree, |
| 9 | + * that currently do not satisfy the max heap property because the child nodes |
| 10 | + * are larger than their parent. For example: if arr is [10,19,52,13,16] then |
| 11 | + * your program should return 19,52. |
| 12 | + * |
| 13 | + * Another example: if arr is [10,19,52,104,14] then your program should return |
| 14 | + * 19,52,104 |
| 15 | + * |
| 16 | + * https://www.coderbyte.com/results/bhanson:Max%20Heap%20Checker:JavaScript |
| 17 | + * |
| 18 | + * @param {array} arr |
| 19 | + * @return {string} |
| 20 | + */ |
| 21 | +function maxHeapChecker(arr) { |
| 22 | + // https://en.wikipedia.org/wiki/Binary_heap#Heap_implementation |
| 23 | + |
| 24 | + // Iterative solution: breadth-first search |
| 25 | + |
| 26 | + const invalidNodes = []; |
| 27 | + |
| 28 | + // Initialize to root, each successive queue will have the next level depth of indexes |
| 29 | + let queue = [0]; |
| 30 | + |
| 31 | + arr.forEach(_ => { |
| 32 | + const nextQueue = []; |
| 33 | + |
| 34 | + queue.forEach(nodeIndex => { |
| 35 | + const leftIndex = 2 * nodeIndex + 1; |
| 36 | + const rightIndex = 2 * nodeIndex + 2; |
| 37 | + |
| 38 | + if (leftIndex < arr.length) { |
| 39 | + if (arr[leftIndex] > arr[nodeIndex]) { |
| 40 | + invalidNodes.push({ |
| 41 | + index: leftIndex, |
| 42 | + value: arr[leftIndex] |
| 43 | + }); |
| 44 | + } |
| 45 | + nextQueue.push(leftIndex); |
| 46 | + } |
| 47 | + |
| 48 | + if (rightIndex < arr.length) { |
| 49 | + if (arr[rightIndex] > arr[nodeIndex]) { |
| 50 | + invalidNodes.push({ |
| 51 | + index: rightIndex, |
| 52 | + value: arr[rightIndex] |
| 53 | + }); |
| 54 | + } |
| 55 | + nextQueue.push(rightIndex); |
| 56 | + } |
| 57 | + }); |
| 58 | + |
| 59 | + queue = nextQueue; |
| 60 | + }); |
| 61 | + |
| 62 | + if (invalidNodes.length === 0) { |
| 63 | + return 'max'; |
| 64 | + } |
| 65 | + |
| 66 | + return invalidNodes.map(node => node.value).join(','); |
| 67 | +} |
| 68 | + |
| 69 | +module.exports = maxHeapChecker; |
0 commit comments