diff --git a/day48/README.md b/day48/README.md new file mode 100644 index 0000000..b6164c8 --- /dev/null +++ b/day48/README.md @@ -0,0 +1,33 @@ +Question of the day: http://www.techiedelight.com/check-given-array-represents-min-heap-not/ + +Given an array of integers, check if it represents a Min-Heap +or not. + +For example, this array represents a min heap: +`[2, 3, 4, 5, 10, 15]` + +While this array doesn't: +`[2, 10, 4, 5, 3, 15]` + +## Ideas + +A min heap is a binary tree in which every parent node has two children +that have values greater than the parent. The second array failed the heap +check because the parent node with value `10` has children `5` and `3`, both +of which are smaller than it. + +I think we can do a linear time check across all parent-children node +relationships in the heap. + +Basically, check if the left sub-tree is a heap, check if the right sub-tree +is a heap, and then check if this node has the correct relationship with its +children. + +I wonder if I can get a recursive solution to work with array and index +manipulation.. + +## Code + +[Python](./day48.py) + +## Follow up diff --git a/day48/isMinHeap.py b/day48/isMinHeap.py new file mode 100644 index 0000000..1566dd0 --- /dev/null +++ b/day48/isMinHeap.py @@ -0,0 +1,26 @@ +def isMinHeap(arr): + def subTreeIsHeap(index, arr, arraySize): + if index >= arraySize: + return True + + left, right = index*2 + 1, index*2 + 2 + leftBigger, rightBigger = True, True + if left < arraySize: + leftBigger = (arr[index] <= arr[left]) + if right < arraySize: + rightBigger = (arr[index] <= arr[right]) + + return leftBigger and rightBigger and subTreeIsHeap(left, arr, size) and subTreeIsHeap(right, arr, size) + + size = len(arr) + return arr[0] <= arr[1] and arr[0] <= arr[2] and subTreeIsHeap(1, arr, size) and subTreeIsHeap(2, arr, size) + +def testIsMinHeap(): + assert isMinHeap([2, 3, 4, 5, 10, 15]) + assert not isMinHeap([2, 10, 4, 5, 3, 15]) + +def tests(): + testIsMinHeap() + +if __name__ == "__main__": + tests() diff --git a/potatofolder/potatotron.txt b/potatofolder/potatotron.txt new file mode 100644 index 0000000..e69de29