Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
In the python solution, in the function `insert_num`, I couldn't understand the ...

Azimul Haque

Apr 9, 2022

In the python solution, in the function insert_num, I couldn't understand the logic in this line, as there are no comments to understand the code, reaching out for your help.

if not self.maxHeap or -self.maxHeap[0] >= num:

The first part if not self.maxHeap I believe is checking if the maxHeap is empty or not. Am i correct?

The second part of logic -self.maxHeap[0] >= num, I didn't understand at all. What is it doing?

  • What is self.maxHeap[0]? is it the first element of maxHeap from begining? i.e. smallest value in maxHeap?
  • Why did we add a negative sign in -self.maxHeap[0]?
  • Why are we checking if -self.maxHeap[0] is >= num?

Please elaborate.

2

0

Comments
Comments
B
Bill 4 years ago

The python heap implementation is a minheap, so the smallest number will always be at the top of the heap. But for the maxheap, we need the largest numbers to be at the top. Rather than implementing a maxheap ourselves, we can fake a maxheap using a minheap by reversi...

On this page