Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions day48/README.md
Original file line number Diff line number Diff line change
@@ -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
26 changes: 26 additions & 0 deletions day48/isMinHeap.py
Original file line number Diff line number Diff line change
@@ -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()
Empty file added potatofolder/potatotron.txt
Empty file.