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

0% completed

Vote For New Content
Renat Zamaletdinov
Why max heaps?

Renat Zamaletdinov

Mar 7, 2024

I think using max heaps is more confusing rather than using min heap, and also, min heaps don't require pushing again any of the intervals

from heapq import heappop, heappush #class Interval: #  def __init__(self, start, end): #    self.start = start #    self.end = end class Solution:   def findNextInterval(self, intervals):     n = len(intervals)     result = [-1] * n     end_heap = []     begin_heap = []     for i in range(n):       b, e = intervals[i].start, intervals[i].end       heappush(end_heap, (e, i))       heappush(begin_heap, (b, i))     while end_heap:       e, i = heappop(end_heap)       while begin_heap and begin_heap[0][0] < e:           heappop(begin_heap)       if begin_heap and begin_heap[0][0] >= e:           result[i] = begin_heap[0][1]         return result

8

0

Comments
Comments

On this page