Heaps Flashcards

1
Q

What kind of binary tree is a heap?

A

Complete binary tree – every level (except possibly the last) is completely filled and all nodes are as far left as possible

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the heap property say about each node?

A

Each node is at least as great as th ekeys stored in its children

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the indices of the children of a parent in an array representation of a heap?

A

2i + 1 and 2i + 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the index of a child’s parent?

A

(i-1)//2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Time complexity of insertion in max-heap?

A

O(logN)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why is the time complexity of an insertion in a max-heap O(logN)?

A
  1. Insert the new element at the bottom left-most node
  2. Then swim the new node up to maintain heap property

In the worst-case you have to swim all the way up which requires H compares where H is the height of the heap

Since heap is a complete binary tree and complete binary trees are balanced it has O(logN) height

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Time complexity of lookup for max element

A

O(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Time complexity of deletion of max element in max-heap?

A

O(logN)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why is deletion of max element in max-heap O(logN)?

A

Must swap max element with last element and then sink last element back down the height of tree (which has height of O(logN))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

When should you use a heap?

A
  1. When all you care about is the largest or smallest elements (O(1))
  2. You do not need fast lookup, delete or search
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What kind of heap does heapq.heapify([]) mutate in to?

A

min-heap

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can you use heapq.heapify([]) to create a max-heap?

A

Negate the priority/weight

ex:

heapq. heapify(arr)
heapq. heappush(arr, (-1, ‘value’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the time complexity of heapq.heapify([])

A

O(n)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly