ProgrammingHardAmazon OA · Flipkart coding round

Dijkstra's algorithm with heapq has no decrease-key operation. Which approach is the standard one in Python?

  1. A. Push a new (distance, node) pair whenever a shorter distance is found, and skip popped pairs whose distance is larger than the best known one
  2. B. Call heapq.update(heap, node, newdist) so the existing entry moves up the heap
  3. C. Remove the old entry with list.remove and call heapify on the whole heap each time
  4. D. Store distances in a dict and rebuild the heap from scratch after every edge relaxation

Correct answer: A. Push a new (distance, node) pair whenever a shorter distance is found, and skip popped pairs whose distance is larger than the best known one

Lazy deletion: the heap may hold several stale entries for a node, and the first pop with the current best distance is used while the rest are discarded. This keeps each push and pop at O(log E).

More Python Programming questions

Exams that ask this topic