Skip to content

Commit 663e57b

Browse files
author
Albert Hu
authored
Merge pull request #34 from alberthu16/day48
Day 48: check if an array is a min heap
2 parents 3b1a40b + da8186f commit 663e57b

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

day48/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
Question of the day: http://www.techiedelight.com/check-given-array-represents-min-heap-not/
2+
3+
Given an array of integers, check if it represents a Min-Heap
4+
or not.
5+
6+
For example, this array represents a min heap:
7+
`[2, 3, 4, 5, 10, 15]`
8+
9+
While this array doesn't:
10+
`[2, 10, 4, 5, 3, 15]`
11+
12+
## Ideas
13+
14+
A min heap is a binary tree in which every parent node has two children
15+
that have values greater than the parent. The second array failed the heap
16+
check because the parent node with value `10` has children `5` and `3`, both
17+
of which are smaller than it.
18+
19+
I think we can do a linear time check across all parent-children node
20+
relationships in the heap.
21+
22+
Basically, check if the left sub-tree is a heap, check if the right sub-tree
23+
is a heap, and then check if this node has the correct relationship with its
24+
children.
25+
26+
I wonder if I can get a recursive solution to work with array and index
27+
manipulation..
28+
29+
## Code
30+
31+
[Python](./day48.py)
32+
33+
## Follow up

day48/isMinHeap.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
def isMinHeap(arr):
2+
def subTreeIsHeap(index, arr, arraySize):
3+
if index >= arraySize:
4+
return True
5+
6+
left, right = index*2 + 1, index*2 + 2
7+
leftBigger, rightBigger = True, True
8+
if left < arraySize:
9+
leftBigger = (arr[index] <= arr[left])
10+
if right < arraySize:
11+
rightBigger = (arr[index] <= arr[right])
12+
13+
return leftBigger and rightBigger and subTreeIsHeap(left, arr, size) and subTreeIsHeap(right, arr, size)
14+
15+
size = len(arr)
16+
return arr[0] <= arr[1] and arr[0] <= arr[2] and subTreeIsHeap(1, arr, size) and subTreeIsHeap(2, arr, size)
17+
18+
def testIsMinHeap():
19+
assert isMinHeap([2, 3, 4, 5, 10, 15])
20+
assert not isMinHeap([2, 10, 4, 5, 3, 15])
21+
22+
def tests():
23+
testIsMinHeap()
24+
25+
if __name__ == "__main__":
26+
tests()

0 commit comments

Comments
 (0)