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

0% completed

Vote For New Content
I think the implementation given is confusing, and only a single min heap is nee...

Pete Stenger

Aug 28, 2022

I think the implementation given is confusing, and only a single min heap is needed with no time complexity additions. A much simpler implementation would:

  1. put all intervals into a min-heap sorted by start time. In this same loop, keep track of the minimum intervalEnd

  2. Pop from the min heap while heapTop().st art < intervalEnd

  3. For every interval...

3a) get the interval end of the top of the heap O(1) * O(N) 3b) pop off the min heap while heapTop().st art < intervalEnd 3c) Add interval or -1 to solution

def solve(intervals): solution = []

construct heap sorted by start time

minHeap = [] intervalEnd = math.inf for i in range(len(intervals)): [s, e] = intervals[i] heappush(minHeap, H(s, e, i)) intervalEnd = min(intervalEnd, e)

Clean up minHeap so that minHeap[0].start >= intervalEnd

while minHeap[0].start < intervalEnd: heappop(minHeap)

Iterate over each interval

for _ in range(len(intervals)): if len(minHeap) > 0: next = heappop(minHeap).end intervalEnd = next.end

while len(minHeap) > 0 and minHeap[0].start < intervalEnd: heappop(minHeap) solution.append(next.i) else: solution.append(-1) return solution

class H: def init(self, start, end, i): self.start = start self.end = end self.i = i def lt(self, other): return self.start < other.start

0

0

Comments
Comments
Design Gurus
Design Gurus3 years ago

Can you create a paste of the solution - https://pastebin.com/

The comment above took away all the indentation.

Please share your paste link here.

M
Mike Xu3 years ago

Hi Pete, I don't think your answer works. When you pop the heap for every heapTop().start < intervalEnd, you are discarding the intervals for which you still need to find the next interval, whether the next interval exists or not. I don't see how your solution finds tha...

On this page