From da8186ff3fe9b34c0d2a397129a63c1334707bc2 Mon Sep 17 00:00:00 2001 From: Albert Hu Date: Tue, 30 May 2017 00:33:06 -0700 Subject: [PATCH 1/2] Day 48: check if an array is a min heap --- day48/README.md | 33 +++++++++++++++++++++++++++++++++ day48/isMinHeap.py | 26 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 day48/README.md create mode 100644 day48/isMinHeap.py 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() From 18561e1bf6b32ac92863fb7608021dba4e8a538e Mon Sep 17 00:00:00 2001 From: Jinsu Elhance Date: Thu, 1 Mar 2018 19:44:26 -0800 Subject: [PATCH 2/2] Day of Potato Potato --- potatofolder/potatotron.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 potatofolder/potatotron.txt diff --git a/potatofolder/potatotron.txt b/potatofolder/potatotron.txt new file mode 100644 index 0000000..e69de29